Advertisement
alisadafi

Matrix-Search-D&C

Nov 9th, 2023
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.59 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. )
  6.  
  7. func main() {
  8.     // Example usage
  9.     X := [][]int{
  10.     {1, 2, 3},
  11.     {4, 5, 6},
  12.     {7, 8, 9},
  13.     }
  14.  
  15.     k := 5
  16.     topLeftI := 0
  17.     topLeftJ := 0
  18.     bottomRightI := len(X) - 1
  19.     bottomRightJ := len(X[0]) - 1
  20.  
  21.     result := find(X, k, topLeftI, topLeftJ, bottomRightI, bottomRightJ)
  22.  
  23.     if result[0] == -1 && result[1] == -1 {
  24.         fmt.Println("Element not found.")
  25.     } else {
  26.         fmt.Printf("Element found at position (%d, %d).\n", result[0], result[1])
  27.     }
  28.     }
  29.  
  30. func find(X [][]int, k, topLeftI, topLeftJ, bottomRightI, bottomRightJ int) [2]int {
  31.     mI := (topLeftI + bottomRightI) / 2
  32.     mJ := (topLeftJ + bottomRightJ) / 2
  33.  
  34.     if X[mI][mJ] == k {
  35.     return [2]int{mI, mJ}
  36.     }
  37.  
  38.     if topLeftI == bottomRightI && topLeftJ == bottomRightJ {
  39.         return [2]int{-1, -1} // not found
  40.     }
  41.  
  42.     if topLeftI > bottomRightI || topLeftJ > bottomRightJ {
  43.         return [2]int{-1, -1} // not found
  44.     }
  45.  
  46.     if X[mI][mJ] > k {
  47.         pos := find(X, k, topLeftI, topLeftJ, mI-1, mJ-1)
  48.         if pos != [2]int{-1, -1} {
  49.             return pos
  50.         }
  51.  
  52.         pos = find(X, k, mI, topLeftJ, bottomRightI, mJ-1)
  53.         if pos != [2]int{-1, -1} {
  54.             return pos
  55.         }
  56.  
  57.         pos = find(X, k, topLeftI, mJ, mI-1, bottomRightJ)
  58.         if pos != [2]int{-1, -1} {
  59.             return pos
  60.         }
  61.         } else {
  62.         pos := find(X, k, mI+1, mJ+1, bottomRightI, bottomRightJ)
  63.         if pos != [2]int{-1, -1} {
  64.             return pos
  65.         }
  66.  
  67.         pos = find(X, k, mI+1, topLeftJ, bottomRightI, mJ)
  68.         if pos != [2]int{-1, -1} {
  69.             return pos
  70.         }
  71.  
  72.         pos = find(X, k, topLeftI, mJ+1, mI, bottomRightJ)
  73.         if pos != [2]int{-1, -1} {
  74.             return pos
  75.         }
  76.     }
  77.  
  78.     return [2]int{-1, -1} // not found
  79. }
  80.  
Tags: D&C
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement