leetcode题目:Search a 2D Matrix II 问题描述如下:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following
properties:
Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
注意到该矩阵在在每个维度上是有序的,先考虑其中某一个维度(即一维)的情况,此时矩阵退化为列表,用二分查找即可解决。
类似地,在一个矩阵内,我们可以根据中点将矩阵分成2^2个子矩阵,每次比较可以剔除一个子矩阵,将剩下三个子矩阵进行递归
地查找。最后结果为三个子矩阵的并。
// 假定数组规模为m*n, m,n为常量
bool solve_matrix(int matrix[m][n], int target, int row_head,
int col_head, int row_end, int col_end){
if(row_head > row_end || col_head > col_end) return false;
int row_mid = (row_head + row_end) / 2;
int col_mid = (col_head + col_end) / 2;
if(matrix[row_mid][col_mid] == target) return true;
else if( matrix[row_mid][col_mid] < target)
return solve_matrix(matrix, target, row_head, col_mid+1, row_mid, col_end) ||
solve_matrix(matrix, target, row_mid +1, col_head, row_end, col_mid) ||
solve_matrix(matrix, target, row_mid+1, col_mid+1, row_end, col_end) ;
else return solve_matrix(matrix, target, row_head, col_mid, row_mid-1, col_end) ||
solve_matrix(matrix, target, row_mid , col_head, row_end, col_mid-1) ||
solve_matrix(matrix, target, row_head, row_head, row_mid-1, col_mid-1) ;
}
特别要注意子矩阵的分法,否则可能造成段错误。第一次调用时row_end = m-1, col_end = n-1 。