2014年2月27日星期四

LeetCode - 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 class Solution {
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        boolean visit[][] = new boolean[m][n];
        for(int i=0;i<m;i++) {
            for(int j=0;j<n;j++) {
                if(visit(board, visit, word, 0, i, j)) {
                    return true;
                }
            }
        }
        return false;
    }
 
    public boolean visit(char[][] board, boolean visit[][], String word, int k, int i, int j) {
        if(k==word.length()) {
            return true;
        }
        int m = board.length;
        int n = board[0].length;
        if(i<0 || i>=m || j<0 || j>=n || visit[i][j]) {
            return false;
        }
        if(word.charAt(k)==board[i][j]) {
            visit[i][j] = true;
            boolean exist = visit(board, visit, word, k+1, i+1, j) || visit(board, visit, word, k+1, i-1, j)
                || visit(board, visit, word, k+1, i, j+1) || visit(board, visit, word, k+1, i, j-1);
            visit[i][j] = false;
            return exist;
        } else {
            return false;
        }
    }
}

=======

public class Solution {
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0 || word == null) {
            return false;
        }
        int row = board.length;
        int column = board[0].length;
        boolean[][] visited = new boolean[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (visit(board, word, visited, 0, i, j)) {
                    return true;
                }
            }
        }
        return false;
    }
   
    private boolean visit(char[][] board, String word, boolean[][] visited, int cur, int i, int j) {
        int row = board.length;
        int column = board[0].length;
        if (i < 0 || i >= row || j < 0 || j >= column || visited[i][j] || board[i][j] != word.charAt(cur)) {
            return false;
        }
        if (cur == word.length() -1) {
            return true;
        }
        visited[i][j] = true;
        boolean res = visit(board, word, visited, cur + 1, i + 1, j) ||
               visit(board, word, visited, cur + 1, i - 1, j) ||
               visit(board, word, visited, cur + 1, i, j + 1) ||
               visit(board, word, visited, cur + 1, i, j - 1);
        visited[i][j] = false;
        return res;
    }
}

没有评论:

发表评论