4-direction template

int[][] DIRS = {{-1,0}, {1,0}, {0,-1}, {0,1}};
// 8-direction: add diagonals
for (int[] d : DIRS) {
  int nr = r + d[0], nc = c + d[1];
  if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
  if (visited[nr][nc] || grid[nr][nc] == WALL) continue;
  visited[nr][nc] = true;
  q.offer(new int[]{nr, nc});
}
Advertisement

Number of islands

For each unvisited land cell, BFS marks entire island. Count starts.

Advertisement

Rotting oranges

Multi-source BFS from all rotten. Answer = max distance (or -1 if fresh remain).

Shortest path with obstacles

Standard BFS. If diagonal weight = √2 → 0-1 BFS or Dijkstra.