Why does this DFS-based island counter merge diagonal cells into one island?

I’m counting islands in a 2D grid, but this implementation seems to treat diagonal neighbors as connected. For the sample below I expect 3 islands, but I get 2. What is the bug in the traversal logic?

function countIslands(g) {
  const seen = new Set();
  const dirs = [-1, 0, 1];
  let count = 0;
  function dfs(r, c) {
    const key = r + ',' + c;
    if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] === '0' || seen.has(key)) return;
    seen.add(key);
    for (const dr of dirs) for (const dc of dirs) if (dr || dc) dfs(r + dr, c + dc);
  }
  for (let r = 0; r < g.length; r++) for (let c = 0; c < g[0].length; c++) if (g[r][c] === '1' && !seen.has(r + ',' + c)) { count++; dfs(r, c); }
  return count;
}

Quelly :blush:

Your nested dr/dc loops visit all 8 neighbors, so diagonals get connected too.

BobaMilk :grinning_face_with_smiling_eyes:

@BobaMilk, that if (dr || dc) skips only the center cell, so a diagonal like (r+1, c+1) still gets traversed and merged.

Sarah