Skip to main content

Word Search

LeetCode 79 | Difficulty: Medium​

Medium

Problem Description​

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:

- `m == board.length`

- `n = board[i].length`

- `1 <= m, n <= 6`

- `1 <= word.length <= 15`

- `board` and `word` consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

Topics: Array, String, Backtracking, Depth-First Search, Matrix


Approach​

Backtracking​

Explore all candidates by building solutions incrementally. At each step, choose an option, explore further, then unchoose (backtrack) to try the next option. Prune branches that can't lead to valid solutions.

When to use

Generate all combinations/permutations, or find solutions that satisfy constraints.

Matrix​

Treat the matrix as a 2D grid. Common techniques: directional arrays (dx, dy) for movement, BFS/DFS for connected regions, in-place marking for visited cells, boundary traversal for spiral patterns.

When to use

Grid traversal, island problems, path finding, rotating/transforming matrices.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 116 ms)​

MetricValue
Runtime116 ms
Memory29.5 MB
Date2020-09-30
Solution
public class Solution {
public bool Exist(char[][] board, string word) {
int m = board.GetLength(0);
int n = board[0].GetLength(0);
bool[,] visited = new bool[m,n];

for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if(board[i][j]==word[0])
{
if(Exist(board, word, 0, i, j, visited)) return true;
}
}
}
return false;
}

private bool Exist(char[][] board, string word, int pos, int i, int j, bool[,] visited)
{

if(pos == word.Length) return true;
if(i<0 || i>= board.GetLength(0) || j<0 || j>=board[0].GetLength(0) || board[i][j] != word[pos] || visited[i,j])
return false;
visited[i,j] = true;
bool exists = Exist(board, word, pos+1, i+1, j, visited) ||
Exist(board, word, pos+1, i-1, j, visited) ||
Exist(board, word, pos+1, i, j+1, visited) ||
Exist(board, word, pos+1, i, j-1, visited) ;
visited[i,j] = false;
return exists;
}
}
πŸ“œ 2 more C# submission(s)

Submission (2018-10-22) β€” 176 ms, N/A​

public class Solution {
public bool Exist(char[,] board, string word) {
int m = board.GetLength(0);
int n = board.GetLength(1);

for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if(Search(board, i, j, 0, word))
return true;
}
}
return false;
}

public bool Search(char[,] board, int i, int j, int k, string word)
{
if(word.Length==k) return true;
int m = board.GetLength(0);
int n = board.GetLength(1);
if(i<0 || i>=m || j<0 || j>=n || board[i,j] != word[k] || board[i,j] == '#')
return false;
board[i,j] = '#';
bool exist = Search(board, i-1, j, k+1, word) ||
Search(board, i+1, j, k+1, word) ||
Search(board, i, j-1, k+1, word) ||
Search(board, i, j+1, k+1, word);
board[i,j] = word[k];
return exist;
}

}

Submission (2018-01-29) β€” 369 ms, N/A​

public class Solution {
public bool Exist(char[,] board, string word) {

int m = board.GetLength(0);
int n = board.GetLength(1);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
bool[,] visited = new bool[m, n];
if(board[i,j]==word[0] && backtrack(board,word, i, j, 0, visited))
{
return true;
}
}
}

return false;
}

public bool backtrack(char[,] board, string word, int ri, int ci, int index, bool[,] visited)
{
if(index==word.Length)
{
return true;
}
if(ri<0 || ri==board.GetLength(0) || ci<0 || ci==board.GetLength(1) || board[ri, ci] != word[index] || visited[ri,ci])
{
return false;
}
visited[ri,ci] = true;
var result = backtrack(board,word, ri, ci-1, index+1, visited)
|| backtrack(board,word, ri, ci+1, index+1, visited)
|| backtrack(board,word, ri-1, ci, index+1, visited)
|| backtrack(board,word, ri+1, ci, index+1, visited);
visited[ri,ci] = false;
return result;

}
}

Complexity Analysis​

ApproachTimeSpace
Backtracking$O(n! or 2^n)$$O(n)$
Graph BFS/DFS$O(V + E)$$O(V)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Identify pruning conditions early to avoid exploring invalid branches.