I’m implementing a word search on a 2D board with DFS/backtracking. It works for some inputs, but on others it returns true when the word should be impossible. I suspect my visited tracking is leaking across branches. What exactly is wrong with this recursion?
function exists(board, word) {
const seen = new Set();
function dfs(r, c, i) {
if (i === word.length) return true;
const key = r + ',' + c;
if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) return false;
if (seen.has(key) || board[r][c] !== word[i]) return false;
seen.add(key);
return dfs(r+1,c,i+1) || dfs(r-1,c,i+1) || dfs(r,c+1,i+1) || dfs(r,c-1,i+1);
}
}
Should seen be copied per call, or is there a cleaner fix?
Hari