Hi everyone i'm trying to solve a problem where i have to find the number of cells that have same value given i can only move up down left and right in a matrix.I know i can solving it using bfs .But i'm not getting correct answer so for example
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}
};
This should return 3 because if i will start from cell (2,1) i'll get 39,39,39 by moving up, down ,left and right and my method looks like find_cells(int[][] matrix, int row, int col) where row and col are starting points.Do not use any helper method.I'm getting 1 may be because i'm marking the neighbors as true and next time when i try to access them it skips them.Sorry for the indentation.
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;
}