For starters, I am not trying to ask the difference between a car and a DeLorean. So, I am solving this LeetCode question:
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]Given word = "ABCCED", return true.
A highly upvoted solution is as follows:
public class Solution {
public boolean exist(char[][] board, String word) {
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length; j++){
if(exist(board, i, j, word, 0))
return true;
}
return false;
}
private boolean exist(char[][] board, int i, int j, String word, int ind){
if(ind == word.length()) return true;
if(i > board.length-1 || i <0 || j<0 || j >board[0].length-1 || board[i][j]!=word.charAt(ind))
return false;
board[i][j]='*';
boolean result = exist(board, i-1, j, word, ind+1) ||
exist(board, i, j-1, word, ind+1) ||
exist(board, i, j+1, word, ind+1) ||
exist(board, i+1, j, word, ind+1);
board[i][j] = word.charAt(ind); //--> why?
return result;
}
My question is - what was the intuition behind using a backtracking algo for this question, as against using a normal recursive DFS? While using recursive DFS, I would just have marked the nodes as visited and then moved on to its neighbors (thereby figuring out ABCCED
is a valid path). Why do I have to backtrack (commented line in code above) to realize if this path exists?
Thanks!
Edit: Other way of asking my question is this way: Why don't we start from the topmost left cell A
and start visiting all its neighbors using a visited
set along the way to mark visited nodes? In the next iteration, we could start from the cell adjacent to topmost left A
- B
, visit all its neighbors using a new visited
set to mark visited nodes and so on? Why use backtracking?