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 ![]()