LeetCode 79 - Word Search

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.

public boolean exist(char[][] board, String word) {
    int m=board.length, n=board[0].length;
    boolean[][] used = new boolean[m][n];
    for(int i=0; i<m; i++) {
        for(int j=0; j<n; j++) {
            if(search(board, used, word, 0, i, j)) return true;
        }
    }
    return false;
}

public boolean search(char[][] board, boolean[][] used, String s, int index, int i, int j) {
    if(index == s.length()) return true;
    if(i<0 || j<0 || i==board.length || j == board[0].length 
        || used[i][j] || board[i][j] != s.charAt(index)) return false;
    used[i][j] = true;
    boolean result = search(board, used, s, index+1, i+1, j) || 
                    search(board, used, s, index+1, i-1, j) || 
                    search(board, used, s, index+1, i, j+1) || 
                    search(board, used, s, index+1, i, j-1);
    used[i][j] = false;
    return result;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2201609