DevPath

← All problems

Word Search

Medium backtracking · matrix

Description

Given a grid of letters and a word, return true if the word can be formed from adjacent (horizontally or vertically) cells without reusing a cell.

Constraints

1 <= rows, cols <= 6; word length >= 1

Examples

Input: board = ["ABCE","SFCS","ADEE"], word = "ABCCED"

Output: true

Hints (1)
  • Depth-first search from each cell, marking visited cells.

Solutions

DFS with in-place marking. · Time O(rows*cols*4^len) · Space O(len)

func exist(board []string, word string) bool {
    rows, cols := len(board), len(board[0])
    grid := make([][]byte, rows)
    for i := range board {
        grid[i] = []byte(board[i])
    }
    var dfs func(r, c, i int) bool
    dfs = func(r, c, i int) bool {
        if i == len(word) {
            return true
        }
        if r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] != word[i] {
            return false
        }
        tmp := grid[r][c]
        grid[r][c] = '#'
        found := dfs(r+1, c, i+1) || dfs(r-1, c, i+1) || dfs(r, c+1, i+1) || dfs(r, c-1, i+1)
        grid[r][c] = tmp
        return found
    }
    for r := 0; r < rows; r++ {
        for c := 0; c < cols; c++ {
            if dfs(r, c, 0) {
                return true
            }
        }
    }
    return false
}

Create a free account to submit solutions, track progress and save problems.

Create account