An interactive visualization of DFS backtracking on a character grid. Watch the algorithm explore paths letter by letter, backtracking when a path doesn't match the target word.
DFS LeetCode 79 โ Mediumm x n grid of characters board and a string word,
return true if word exists in the grid.fun exist(board: Array<CharArray>, word: String): Boolean { val rows = board.size; val cols = board[0].size fun dfs(r: Int, c: Int, i: Int): Boolean { if (i == word.length) { return true } if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[i]) { return false } val temp = board[r][c] board[r][c] = '#' // mark visited val found = (dfs(r + 1, c, i + 1) || dfs(r - 1, c, i + 1) || dfs(r, c + 1, i + 1) || dfs(r, c - 1, i + 1)) board[r][c] = temp // backtrack return found } for (r in 0 until rows) { for (c in 0 until cols) { if (dfs(r, c, 0)) { return true } } } return false}
DFS with backtracking โ temporarily mark cells as visited to prevent reuse, explore all 4 directions (down, up, right, left), then unmark (backtrack) so the cell is available for other paths. Try every cell as a potential starting point until the word is found or all possibilities are exhausted.
(r, c) in the grid as a potential starting position.(r, c) trying to match word[i]:i == len(word), all characters matched โ return True.board[r][c] != word[i], return False.board[r][c] with '#'.word[i+1].board[r][c] to its original character.
Where m * n is the grid size and L is the word length.
For each of the m * n starting cells, the DFS can branch into 4 directions
at each of the L levels โ worst case 4^L paths.
Space is O(L) for the recursion stack depth (the word length).