Given a 2D board and a word, find if the word exists in the grid.

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

Example:

Given board =

[
  "ABCE",
  "SFCS",
  "ADEE"
]

word = "ABCCED", -> returns true,

word = "SEE", -> returns true,

word = "ABCB", -> returns false.

Solution:

Simple depth search first. At each level, we have to check four directions:

  • top (i - 1, j)
  • bottom (i + 1, j)

  • left (i, j - 1)

  • right (i, j + 1)

Once we found a character we could temperaily set it to '#' and set it back after that branch is finished.

Code:

public class Solution {

    private boolean result = false;

    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0) {
            return false;
        }
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    go(board, 0, word, i, j);
                }
            }
        }
        return result;
    }

    private void dfs(char[][] board, int index, String word, int i, int j) {
        if (index >= word.length()) {
            result = true;
            return;
        }
        go(board, index, word, i - 1, j);
        go(board, index, word, i + 1, j);
        go(board, index, word, i, j - 1);
        go(board, index, word, i, j + 1);
    }

    private void go(char[][] board, int index, String word, int i, int j) {
        if (result) {
            return;
        }
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0) {
            return;
        }
        char curt = word.charAt(index);
        if (curt == board[i][j]) {
            board[i][j] = '#';
            dfs(board, index + 1, word, i, j);
            board[i][j] = curt;
        }
    }
}

results matching ""

    No results matching ""