The Problem

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.

Interactive Visualization

Speed:
Character Grid
Code
fun exist(board: Array<CharArray>, word: String): Boolean {    val rows = board.size; val cols = board[0].size    fun dfs(r: Int, c: Int, i: Int): Boolean {        if (i == word.length) {            return true        }        if (r < 0 || r >= rows ||            c < 0 || c >= cols ||            board[r][c] != word[i]) {            return false        }        val temp = board[r][c]        board[r][c] = '#'  // mark visited        val 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))        board[r][c] = temp  // backtrack        return found    }    for (r in 0 until rows) {        for (c in 0 until cols) {            if (dfs(r, c, 0)) {                return true            }        }    }    return false}
Current Step
Press Step or Play to begin.

How It Works

Key Insight

DFS with backtracking โ€” temporarily mark cells as visited to prevent reuse, explore all 4 directions (down, up, right, left), then unmark (backtrack) so the cell is available for other paths. Try every cell as a potential starting point until the word is found or all possibilities are exhausted.

The Algorithm

  • Iterate over every cell (r, c) in the grid as a potential starting position.
  • DFS from (r, c) trying to match word[i]:
  • โ€” Base case: if i == len(word), all characters matched โ€” return True.
  • โ€” Bounds/mismatch check: if out of bounds or board[r][c] != word[i], return False.
  • โ€” Mark visited: temporarily replace board[r][c] with '#'.
  • โ€” Explore: recursively try all 4 neighbors for word[i+1].
  • โ€” Backtrack: restore board[r][c] to its original character.
  • If any starting cell's DFS returns True, the word exists. Otherwise return False.

Complexity

Time O(m * n * 4^L)
Space O(L)

Where m * n is the grid size and L is the word length. For each of the m * n starting cells, the DFS can branch into 4 directions at each of the L levels โ€” worst case 4^L paths. Space is O(L) for the recursion stack depth (the word length).