1. Word Search I Repeated for Every Word
Intuition
For each word in words, scan every cell on the board. If dfs(r, c, 0) finds the word, add to results. Reset visited state between words.
When to apply: Basic baseline check.
Algorithm
- Step 1: Loop over each word in
words. - Step 2: For each cell (r, c) on board: if
dfs(r, c, 0)matches, add word and break. - Step 3: Repeat for all words.
- Step 4: Return collected words.
#include <iostream>#include <vector>#include <string>using namespace std; class Solution { bool dfs(vector<vector<char>>& board, const string& word, int idx, int r, int c) { if (idx == (int)word.length()) return true; if (r < 0 || r >= (int)board.size() || c < 0 || c >= (int)board[0].size() || board[r][c] != word[idx]) { return false; } char temp = board[r][c]; board[r][c] = '#'; bool found = dfs(board, word, idx + 1, r + 1, c) || dfs(board, word, idx + 1, r - 1, c) || dfs(board, word, idx + 1, r, c + 1) || dfs(board, word, idx + 1, r, c - 1); board[r][c] = temp; return found; } public: vector<string> findWords(vector<vector<char>>& board, vector<string>& words) { vector<string> result; int m = board.size(), n = board[0].size(); for (const string& w : words) { bool found = false; for (int r = 0; r < m && !found; r++) { for (int c = 0; c < n && !found; c++) { if (dfs(board, w, 0, r, c)) { result.push_back(w); found = true; } } } } return result; }}; int main() { Solution sol; vector<vector<char>> board = {{'o','a','a','n'},{'e','t','a','e'},{'i','h','k','r'},{'i','f','l','v'}}; vector<string> words = {"oath","pea","eat","rain"}; auto res = sol.findWords(board, words); for (const string& s : res) cout << s << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(W * M * N * 3^L)— Must execute full DFS for every single word in the dictionary. - Space complexity:
O(L)— Recursion stack depth up to maximum word length L.
Why Brute Force Doesn't Scale:
Checking every word individually repeats identical prefix checks millions of times.
Trie-guided search visits shared prefixes once, finding all words across the board in ~35ms.