Leetcode–Word Search

The Problem:

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.

For example,
Given board =


word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false


  1. Use a two dimension boolean to record if each char is used or not. When search its four neighbors, each time find a true, fireĀ a new branch of recursion, only directly return that branch’s result if that gives a true. Because even if this branch fail, other branches can still return true.

Java Solution

public class Solution {
    public boolean exist(char[][] board, String word) {
        if(board==null || board.length==0) return false;
        if(word.length()==0) return true;
        boolean[][] used = new boolean[board.length][board[0].length];
        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[0].length; j++){
                    used = new boolean[board.length][board[0].length];
                    used[i][j] =true;
                    if(findChar(board, word, used, 1, i, j))
                        return true;
        return false;
    private boolean findChar(char[][] board, String word, boolean[][] used, int index, int i, int j){
        if(index == word.length())
            return true;
        if(i>0 && !used[i-1][j] && board[i-1][j]==word.charAt(index)){
            used[i-1][j] = true;
            if(findChar(board, word, used, index+1, i-1, j))
                return true;
            used[i-1][j] = false;
        if(i< board.length-1 && !used[i+1][j] && board[i+1][j]==word.charAt(index)){
            used[i+1][j] = true;
            if(findChar(board, word, used, index+1, i+1, j))
                return true;
            used[i+1][j] = false;
        if(j< board[0].length-1 && !used[i][j+1] && board[i][j+1]==word.charAt(index)){
            used[i][j+1] = true;
            if(findChar(board, word, used, index+1, i, j+1))
                return true;
            used[i][j+1] = false;
        if(j>0 && !used[i][j-1] && board[i][j-1]==word.charAt(index)){
            used[i][j-1] = true;
            if(findChar(board, word, used, index+1, i, j-1))
                return true;
            used[i][j-1] = false;
        return false;