Skip to content
Algorithm.js
Frame

Graph DFS

그래프·격자 DFS에서 base case, 방문 처리, 인접 탐색 흐름을 정리해 재사용 가능한 사고 틀 만들기

Oct 6, 2025 — graph-dfs
const [ ROWS, COLS ] = [ grid.length, grid[0].length ];
const neighbors = [ [1,0], [-1, 0], [0,1], [0, -1] ];
const isValid = (r,c) => !(r < 0 || r >= ROWS || c < 0 || c >= COLS);
const seen = new Set();
const dfs = (r, c) => {
let result = 0;
for (const [ dR, dC ] of neighbors) {
const newR = r + dR;
const newC = c + dC;
if (!isValid(newR, newC)) continue;
if (seen.has([newR, neweC])) continue;
seen.add([newR, newC]);
result += dfs(newR, newC);
}
return result;
}
return dfs(START_NODE);

기본 문제들

Reference