Search
⌘K
Get Premium
Backtracking

Word Search

medium

DESCRIPTION (inspired by Leetcode.com)

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 = [
    ['B', 'L', 'C', 'H'],
    ['D', 'E', 'L', 'T'],
    ['D', 'A', 'K', 'A'],
]
word = "BLEAK"
BLCHDELTDAKA
"BLEAK" can be formed using the tiles in dark blue.

Output:

True

Example 2:

Input:

board = [
    ['B', 'L', 'C', 'H'],
    ['D', 'E', 'L', 'T'],
    ['D', 'A', 'K', 'A'],
]
word = "BLEED"

Output:

False

Explanation

We can solve this problem using a backtracking approach. The idea is to try to find the target word one character at a time using depth-first search.
We'll iterate over each cell in the grid. If any of the letters in these cells are the same as the first letter of our target word, then we can initialize our depth-first search from that cell.

Depth-First Search Function

To perform our depth-first search, we'll create a helper function dfs. This function will take in r and c, which represent the coordinates of the current cell we are looking at, and index, which represents the index within word that we are searching for.
This function checks if the current cell is equal to the letter we are currently searching for. If so, it makes recursive calls to explore each of its 4 neighbors (in the N, W, S, E) directions to look for the next letter in word.
If it isn't, (or the cell is not in the bounds of the grid), then it returns False immediately.
The base case is when index == len(word), which happens when we have found the target word in our grid, so we can return True.

Keeping Track of Visited Cells

Because our grid is a graph, we have to keep track of visited cells in our current word path to avoid an infinite loop.
Instead of keeping a set of visited cells, we can keep track our visited cells by updating the value of the cell to be some placeholder value such as "#". This means that if we ever encounter a cell with "#", then we can return immediately, as we have already visited this cell on our current path.
We just have to make sure that we backtrack appropriately by restoring the value of the cell to its previous (actual letter) value after the recursive calls have finished.
This is important as it "frees" up the cell to be used by another path in the future, if necessary.

Solution

Solution
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
rows, cols = len(board), len(board[0])
def dfs(r, c, index):
if index == len(word):
return True
if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[index]:
return False
temp = board[r][c]
board[r][c] = "#"
found = (
dfs(r+1, c, index+1) or
dfs(r-1, c, index+1) or
dfs(r, c+1, index+1) or
dfs(r, c-1, index+1)
)
board[r][c] = temp
return found
# initialize depth-first search from
# each of the cells that have the same first
# letter as word
for row in range(rows):
for col in range(cols):
if board[row][col] == word[0]:
if dfs(row, col, 0):
return True
return False
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(m * n * 4^L) where m and n are the dimensions of the grid and L is the length of the word. We iterate over each cell once (m * n), and for each cell, we call the dfs function which makes 4 recursive calls with a max depth of L, giving us O(4^L) per cell.

Space Complexity: O(L) where L is the length of the word. We need to account for the space on the recursive call stack, which can be L calls deep in the worst case.

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Reading Progress

On This Page