- 阅读权限
- 255
- 威望
- 0 级
- 论坛币
- 50288 个
- 通用积分
- 83.6306
- 学术水平
- 253 点
- 热心指数
- 300 点
- 信用等级
- 208 点
- 经验
- 41518 点
- 帖子
- 3256
- 精华
- 14
- 在线时间
- 766 小时
- 注册时间
- 2006-5-4
- 最后登录
- 2022-11-6
|
- Listing 3-5. Java Code to Search in a Partially Sorted Matrix (Version 1)
- boolean find_solution1(int matrix[][], int value) {
- int rows = matrix.length;
- int cols = matrix[0].length;
- return findCore(matrix, value, 0, 0, rows - 1, cols - 1);
- }
- boolean findCore(int matrix[][], int value, int row1, int col1, int row2, int col2) {
- if(value < matrix[row1][col1] || value > matrix[row2][col2])
- return false;
- if(value == matrix[row1][col1] || value == matrix[row2][col2])
- return true;
- int copyRow1 = row1, copyRow2 = row2;
- int copyCol1 = col1, copyCol2 = col2;
- int midRow = (row1 + row2) / 2;
- int midCol = (col1 + col2) / 2;
- // find the last element less than value on diagonal
- while((midRow != row1 || midCol != col1)
- && (midRow != row2 || midCol != col2)) {
- if(value == matrix[midRow][midCol])
- return true;
- if(value < matrix[midRow][midCol]) {
- row2 = midRow;
- col2 = midCol;
- }
- else {
- row1 = midRow;
- col1 = midCol;
- }
- midRow = (row1 + row2) / 2;
- midCol = (col1 + col2) / 2;
- }
- // find value in two sub-matrices
- boolean found = false;
- if(midRow < matrix.length - 1)
- found = findCore(matrix, value, midRow + 1, copyCol1, copyRow2, midCol);
- if(!found && midCol < matrix[0].length - 1)
- found = findCore(matrix, value, copyRow1, midCol + 1, midRow, copyCol2);
- return found;
- }
复制代码
|
|