1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length, n = matrix[0].length; return searchMatrix(matrix, 0, m - 1, 0, n - 1, m, n, target); }
private boolean searchMatrix(int[][] matrix, int startRowIndex, int endRowIndex, int startColIndex, int endColIndex, int rows, int cols, int target) { if (startRowIndex < 0 || startRowIndex == rows || startColIndex < 0 || startColIndex == cols || endRowIndex < 0 || endRowIndex == rows || endColIndex < 0 || endColIndex == cols || startRowIndex > endRowIndex || startColIndex > endColIndex) { return false; }
if (startRowIndex == endRowIndex && startColIndex == endColIndex) { return matrix[startRowIndex][startColIndex] == target; }
int midRowIndex = (startRowIndex + endRowIndex) >>> 1; int midColIndex = (startColIndex + endColIndex) >>> 1; if (matrix[midRowIndex][midColIndex] < target) { return searchMatrix(matrix, midRowIndex + 1, endRowIndex, startColIndex, midColIndex, rows, cols, target) || searchMatrix(matrix, startRowIndex, midRowIndex, midColIndex + 1, endColIndex, rows, cols, target) || searchMatrix(matrix, midRowIndex + 1, endRowIndex, midColIndex + 1, endColIndex, rows, cols, target); } else { return searchMatrix(matrix, midRowIndex + 1, endRowIndex, startColIndex, midColIndex - 1, rows, cols, target) || searchMatrix(matrix, startRowIndex, midRowIndex - 1, midColIndex + 1, endColIndex, rows, cols, target) || searchMatrix(matrix, startRowIndex, midRowIndex, startColIndex, midColIndex, rows, cols, target); } } }
|