package main import "fmt" func searchMatrix(matrix [][]int, target int) bool { rows := len(matrix) if rows == 0 { return false } cols := len(matrix[0]) r, c := 0, cols-1 for r < rows && c >= 0 { if matrix[r][c] == target { return true } else if matrix[r][c] > target { c-- } else { r++ } } return false } func main() { matrix := [][]int{ {1, 4, 7, 11}, {2, 5, 8, 12}, {3, 6, 9, 16}, {10, 13, 14, 17}, } fmt.Println(searchMatrix(matrix, 5)) }
The code starts searching from the top-right corner. It moves left if the current number is greater than the target, or down if smaller. Since 5 is in the matrix, it returns true.
package main import "fmt" func searchMatrix(matrix [][]int, target int) bool { rows := len(matrix) if rows == 0 { return false } cols := len(matrix[0]) r, c := 0, cols-1 for r < rows && c >= 0 { if matrix[r][c] == target { return true } else if matrix[r][c] > target { c-- } else { r++ } } return false } func main() { matrix := [][]int{ {1, 4, 7, 11}, {2, 5, 8, 12}, {3, 6, 9, 16}, {10, 13, 14, 17}, } fmt.Println(searchMatrix(matrix, 15)) }
The search moves through the matrix but never finds 15, so it returns false.
Starting at the top-right corner allows the algorithm to discard a row or a column at each step because moving left decreases values and moving down increases values, matching the sorted property.
package main import "fmt" func searchMatrix(matrix [][]int, target int) bool { rows := len(matrix) if rows == 0 { return false } cols := len(matrix[0]) r, c := 0, cols-1 for r < rows && c >= 0 { if matrix[r][c] == target { return true } else if matrix[r][c] > target { c-- } else { r++ } } return false } func main() { matrix := [][]int{ {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, } fmt.Println(searchMatrix(matrix, 3)) }
The code sets c = cols, which is out of bounds since valid indices are 0 to cols-1. Accessing matrix[r][c] causes an index out of range runtime error.
Starting from bottom-left, if current element is greater than target, move up; if less, move right. This way, all occurrences can be counted efficiently in O(m+n) time.