【发布时间】:2020-05-02 07:16:22
【问题描述】:
大家好,我正在尝试解决一个问题,即我必须找到具有相同值的单元格的数量,因为我只能在矩阵中左右上下移动。我知道我可以使用 bfs 解决它。但是我没有得到正确的答案,例如
int[][] matrix = {
{2 , 3, 4, 10, 12},
{20 , 30, 14, 11, 13},
{29 , 39, 40, 12, 24},
{40 , 39, 39, 15, 35},
{100 ,23, 24, 60, 80}
};
这应该返回 3,因为如果我从单元格 (2,1) 开始,我将通过向上、向下、向左和向右移动得到 39,39,39,我的方法看起来像 find_cells(int[][] 矩阵, int row, int col) 其中 row 和 col 是起点。不要使用任何辅助方法。我得到 1 可能是因为我将邻居标记为真,下次当我尝试访问它们时它会跳过它们.抱歉缩进。
public int find_cells(int[][] matrix, int row, int col){
//invalid row and col
if (row < 0 | col < 0 | row > matrix.length | col > matrix[0].length)
return -1;
// check if cell is already visited.
boolean[][] visited = new boolean[matrix.length][matrix[0].length];
//left and right neighbours
int[] lr_neighbour = {0, 0, -1,1};
//top and bottom neighbours
int[] tb_neighbour = {1, -1, 0, 0};
//number of same cells
int modified = 0;
//queue
Queue<Integer> queue = new LinkedList<>();
queue.add(matrix[row][col]);
//mark current cell as visited.
visited[row][col] = true;
//current pixel at (row,col)
int current_cell = matrix[row][col];
while (!queue.isEmpty()){
queue.remove();
for (int index = 0;index < 4;index++){
row = row+tb_neighbour[index];
col = col+lr_neighbour[index];
if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length || visited[row][col])
continue;
if (current_cell == matrix[row][col]){
//mark all other valid cells as visited.
queue.add(matrix[row][col]);
modified++;
}
visited[row][col] = true;
}
}
return modified;
}
【问题讨论】:
标签: java data-structures queue breadth-first-search