1. DFS with 2D Visited Array
Intuition
Maintain visited[r][c]. If board[r][c] == word[k] && !visited[r][c], mark visited[r][c] = true, recurse to neighbors, and reset on backtrack.
Algorithm
- Step 1: Iterate through every cell (r, c) in the grid to find matching word[0].
- Step 2: Maintain a 2D boolean array visited of size M x N.
- Step 3: Define dfs(r, c, k): if k == word.length return true.
- Step 4: From (r, c), explore 4 neighbors (Up, Down, Left, Right). If neighbor matches word[k] and is unvisited, recurse.
- Step 5: Backtrack by resetting visited[r][c] = false.
#include <iostream>#include <vector>#include <string> class Solution {public: bool dfs(int r, int c, int k, const std::vector<std::vector<char>>& board, const std::string& word, std::vector<std::vector<bool>>& visited) { if (k == (int)word.length()) return true; if (r < 0 || r >= (int)board.size() || c < 0 || c >= (int)board[0].size()) return false; if (visited[r][c] || board[r][c] != word[k]) return false; visited[r][c] = true; bool found = dfs(r + 1, c, k + 1, board, word, visited) || dfs(r - 1, c, k + 1, board, word, visited) || dfs(r, c + 1, k + 1, board, word, visited) || dfs(r, c - 1, k + 1, board, word, visited); visited[r][c] = false; return found; } bool exist(std::vector<std::vector<char>>& board, std::string word) { int m = board.size(), n = board[0].size(); std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == word[0] && dfs(i, j, 0, board, word, visited)) { return true; } } } return false; }}; int main() { Solution solver; std::vector<std::vector<char>> board = { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }; std::cout << "Word 'ABCCED' exists: " << (solver.exist(board, "ABCCED") ? "true" : "false") << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(M * N * 3^L)— Explores paths up to length L with branching factor 3 at each step. - Space complexity:
O(M * N + L)— O(M*N) memory for the visited matrix.