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.


board =

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.


  1. Backtracking


class Solution {
    public boolean exist(char[][] board, String word) {
        char[] w = word.toCharArray();
        for (int i=0; i<board.length; i++) {
            for (int j=0; j<board[i].length; j++) {
                if (exist(board, i, j, w, 0)) return true;
        return false;

    private boolean exist(char[][] board, int x, int y, char[] word, int i) {
        if (i == word.length) return true;
        if (y<0 || x<0 || x == board.length || y == board[x].length) return false;
        if (board[x][y] != word[i]) return false;
        board[x][y] ^= 256; // flip every bit over
        boolean exist = exist(board, x, y+1, word, i+1) // right
            || exist(board, x, y-1, word, i+1) // left
            || exist(board, x+1, y, word, i+1) // down
            || exist(board, x-1, y, word, i+1); // up
        board[x][y] ^= 256; // flip every bit over to recover the original value
        return exist;

results matching ""

    No results matching ""