Algo-Sim › Recursion & Backtracking

Word Search

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Find a word along adjacent cells: DFS from each start, mark a cell while it is on the path, and restore it when backtracking.

Problem

Given a grid of letters board and a string word, return true if word can be spelled by moving between horizontally or vertically adjacent cells, using each cell at most once in the word.

Constraints

Edge cases to test

Follow-up questions

How do you search many words at once?
Put the words in a trie and DFS the board once, following trie edges (LC 212).
How do you prune early?
Check that the board has enough of each letter, and start from the rarer end of the word.

Solution

Java

boolean exist(char[][] board, String word) {
    for (int r = 0; r < board.length; r++) {
        for (int c = 0; c < board[0].length; c++) {
            if (dfs(board, word, r, c, 0)) return true;
        }
    }
    return false;
}

boolean dfs(char[][] board, String word, int r, int c, int k) {
    if (k == word.length()) return true;
    if (r < 0 || c < 0 || r >= board.length || c >= board[0].length
            || board[r][c] != word.charAt(k)) return false;
    char saved = board[r][c];
    board[r][c] = '#';
    boolean found = dfs(board, word, r + 1, c, k + 1) || dfs(board, word, r - 1, c, k + 1)
            || dfs(board, word, r, c + 1, k + 1) || dfs(board, word, r, c - 1, k + 1);
    board[r][c] = saved;
    return found;
}

Python

def exist(board, word):
    rows, cols = len(board), len(board[0])

    def dfs(r, c, k):
        if k == len(word):
            return True
        if (r < 0 or c < 0 or r >= rows or c >= cols
                or board[r][c] != word[k]):
            return False
        saved = board[r][c]
        board[r][c] = "#"
        found = (dfs(r + 1, c, k + 1) or dfs(r - 1, c, k + 1)
                 or dfs(r, c + 1, k + 1) or dfs(r, c - 1, k + 1))
        board[r][c] = saved
        return found

    for r in range(rows):
        for c in range(cols):
            if dfs(r, c, 0):
                return True
    return False

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool exist(vector<vector<char>> &board, string &word) {
        for (int r = 0; r < int(board.size()); r++) {
            for (int c = 0; c < int(board[0].size()); c++) {
                if (dfs(board, word, r, c, 0))
                    return true;
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>> &board, string &word, int r, int c, int k) {
        if (k == int(word.size()))
            return true;
        if (r < 0 || c < 0 || r >= int(board.size()) || c >= int(board[0].size()) || board[r][c] != word[k])
            return false;
        char saved = board[r][c];
        board[r][c] = '#';
        bool found = dfs(board, word, r + 1, c, k + 1) || dfs(board, word, r - 1, c, k + 1)
                     || dfs(board, word, r, c + 1, k + 1) || dfs(board, word, r, c - 1, k + 1);
        board[r][c] = saved;
        return found;
    }
};

More Recursion & Backtracking problems