Skip to main content

Checking Around Grid

  • Put in the constraints first around and exit if it is either lower than 0 or greater than grid length
  • do not manually check coordinates, put it in an array

Code​

private int[] x = new int[]{-1,0,1,0};
private int[] y = new int[]{0,1,0,-1};

public void visitAround(int[][] grid, int r, int c, int placer){
for(int i = 0; i < 4;i++){
int row = x[i] + r;
int col = y[i] + c;
if(row < 0 || row >= grid.length) continue;
if(col < 0 || col >= grid[row].length) continue;
if(visited[row][col]) continue;
if(grid[row][col] != 0){
grid[row][col] = placer;
visited[row][col] = true;
visitAround(grid, row, col, placer);
}
}
}