Word Search in Grid Using Backtracking in DSA C - Time & Space Complexity
We want to know how long it takes to find a word in a grid by trying all possible paths.
How does the search time grow as the grid or word gets bigger?
Analyze the time complexity of the following code snippet.
bool dfs(char** board, int rows, int cols, int r, int c, char* word, int index) {
if (index == strlen(word)) return true;
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[index]) return false;
char temp = board[r][c];
board[r][c] = '#';
bool found = dfs(board, rows, cols, r+1, c, word, index+1) ||
dfs(board, rows, cols, r-1, c, word, index+1) ||
dfs(board, rows, cols, r, c+1, word, index+1) ||
dfs(board, rows, cols, r, c-1, word, index+1);
board[r][c] = temp;
return found;
}
bool exist(char** board, int rows, int cols, char* word) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (dfs(board, rows, cols, i, j, word, 0)) return true;
}
}
return false;
}
This code tries to find the word in the grid by searching from each cell and exploring all directions recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive depth-first search (DFS) exploring up to 4 directions from each cell.
- How many times: For each cell in the grid (rows * cols), DFS explores paths up to the length of the word (k), branching up to 4 directions at each step.
As the grid size or word length grows, the search tries many possible paths, growing very fast.
| Input Size (n = rows*cols, k = word length) | Approx. Operations |
|---|---|
| n=10, k=3 | About 10 * 4^3 = 640 |
| n=100, k=5 | About 100 * 4^5 = 102,400 |
| n=1000, k=6 | About 1000 * 4^6 = 4,096,000 |
Pattern observation: The operations grow exponentially with the word length and linearly with the grid size.
Time Complexity: O(n * 4^k)
This means the search time grows linearly with the number of cells and exponentially with the word length.
[X] Wrong: "The search only checks each cell once, so it is O(n)."
[OK] Correct: The search explores many paths from each cell, branching multiple times, so it repeats work exponentially with word length.
Understanding this complexity helps you explain how backtracking explores many possibilities and why pruning or constraints matter in real problems.
"What if we limited the search to only move right and down? How would the time complexity change?"
Practice
Solution
Step 1: Understand backtracking in grid search
Backtracking tries all possible paths from a starting point to find the target word.Step 2: Compare options with backtracking purpose
Only To explore all possible paths to find the word in the grid describes exploring all paths, which matches backtracking's goal.Final Answer:
To explore all possible paths to find the word in the grid -> Option BQuick Check:
Backtracking = explore all paths [OK]
- Thinking backtracking sorts or counts words
- Confusing backtracking with simple search
- Assuming backtracking modifies the grid permanently
Solution
Step 1: Understand zero-based indexing in C arrays
Arrays start at index 0, so valid indices are from 0 to rows-1 and 0 to cols-1.Step 2: Check each option for correct boundary conditions
if (row >= 0 && row < rows && col >= 0 && col < cols) correctly uses >= 0 and < rows/cols. Others use > 0 or <= rows which are incorrect for zero-based arrays.Final Answer:
if (row >= 0 && row < rows && col >= 0 && col < cols) -> Option DQuick Check:
Check boundaries with >=0 and < size [OK]
- Using > 0 instead of >= 0 excludes first row/column
- Using <= rows includes out-of-bound index
- Mixing 1-based and 0-based indexing
char grid[3][3] = {{'A','B','C'},{'D','E','F'},{'G','H','I'}};
int found = searchWord(grid, 3, 3, "BEF");
printf("%d", found);
Assuming searchWord correctly implements backtracking to find the word in the grid.Solution
Step 1: Analyze the grid and the word "BEF"
The grid rows are: ABC, DEF, GHI. The word "BEF" requires letters B, E, F in sequence adjacent horizontally or vertically.Step 2: Check if "BEF" exists in adjacent cells
B is at (0,1), E is at (1,1), F is at (1,2). B to E is vertical down, E to F is horizontal right, so path exists.Step 3: Confirm if backtracking finds the word
Backtracking can follow B(0,1) -> E(1,1) -> F(1,2), so word is found.Final Answer:
1 -> Option AQuick Check:
Word found = 1 [OK]
- Assuming letters must be in same row only
- Ignoring vertical or diagonal adjacency rules
- Confusing output 0 and 1 meaning
bool dfs(char grid[][], int row, int col, int index, char* word) {
if (index == strlen(word)) return true;
if (row < 0 || row >= rows || col < 0 || col >= cols) return false;
if (grid[row][col] != word[index]) return false;
char temp = grid[row][col];
grid[row][col] = '#';
bool found = dfs(grid, row+1, col, index+1, word) ||
dfs(grid, row-1, col, index+1, word) ||
dfs(grid, row, col+1, index+1, word) ||
dfs(grid, row, col-1, index+1, word);
grid[row][col] = temp;
return found;
}Solution
Step 1: Check function parameter declaration
In C, 2D arrays must have fixed column size in parameters, e.g., char grid[][cols]. Missing column size causes compilation error.Step 2: Verify other parts of the code
Base case with index == strlen(word) is correct. Grid cell is restored after recursion. Diagonal check is optional, not a bug.Final Answer:
The grid parameter lacks column size, causing compilation error -> Option CQuick Check:
2D array params need column size [OK]
- Ignoring 2D array parameter syntax in C
- Thinking base case condition is wrong
- Assuming diagonal moves are mandatory
{ {'C','A','T','F'},
{'B','G','E','S'},
{'I','T','A','E'},
{'S','O','N','G'} }
Which of the following words can be found using backtracking with adjacent horizontal or vertical moves only?Solution
Step 1: Check each word's presence in the grid with adjacency rules
"SONG": S(3,0), O(3,1), N(3,2), G(3,3) - all adjacent horizontally, so possible.
"BATS": B(1,0) has no adjacent A (neighbors: C(0,0), I(2,0), G(1,1)), so no.
"CATS": C(0,0), A(0,1), T(0,2) adjacent, but T(0,2) has no adjacent S (neighbors: A(0,1), F(0,3), E(1,2), A(2,2)), so no.
"FATE": F(0,3) has no adjacent A (neighbors: T(0,2), S(1,3)), so no.Step 2: Identify which word is fully connected by adjacent moves
Only "SONG" has all letters adjacent in sequence.Final Answer:
"SONG" -> Option AQuick Check:
Check adjacency path for each word [OK]
- Assuming diagonal moves allowed
- Ignoring adjacency between letters
- Choosing words with missing adjacent letters
Ready to prove it?
Pass the test and this pattern moves unknown
