LeetCode – Word Search (Java)

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 =

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

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

Analysis

This problem can be solve by using a typical DFS method.

Java Solution

public boolean exist(char[][] board, String word) {
    int m = board.length;
    int n = board[0].length;
 
    boolean result = false;
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
           if(dfs(board,word,i,j,0)){
               result = true;
           }
        }
    }
 
    return result;
}
 
public boolean dfs(char[][] board, String word, int i, int j, int k){
    int m = board.length;
    int n = board[0].length;
 
    if(i<0 || j<0 || i>=m || j>=n){
        return false;
    }
 
    if(board[i][j] == word.charAt(k)){
        char temp = board[i][j];
        board[i][j]='#';
        if(k==word.length()-1){
            return true;
        }else if(dfs(board, word, i-1, j, k+1)
        ||dfs(board, word, i+1, j, k+1)
        ||dfs(board, word, i, j-1, k+1)
        ||dfs(board, word, i, j+1, k+1)){
            return true;
        }
        board[i][j]=temp;
    }
 
    return false;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Haomin on 2015-11-21

    public boolean dfs(char[][] board, String word, int i, int j, int k){
    int m = board.length;
    int n = board[0].length;

    if(i<0 || j=m || j>=n){
    return false;
    }

    if(board[i][j] == word.charAt(k)){
    board[i][j]=’#’;
    if(k==word.length()-1){
    return true;
    }else if(dfs(board, word, i-1, j, k+1)
    ||dfs(board, word, i+1, j, k+1)
    ||dfs(board, word, i, j-1, k+1)
    ||dfs(board, word, i, j+1, k+1)){
    return true;
    }
    board[i][j]=word.charAt(k);
    }

    return false;
    }

  2. Vipin s on 2016-1-12

    ABCCEDFB?–> should not be found

  3. Vipin s on 2016-1-12

    Sorry got it

  4. Faraz on 2017-2-21

    Why is the following check being done?


    if(k==word.length()-1){
    return true;
    }

  5. Goog on 2017-3-10

    Is there any advantage of using DFS here over BFS other than DFS is easier to implement with backtracking?

Leave a comment

*