2015年6月30日星期二

Word Search leetcode

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.
这道题的原理就是利用深度优先搜索, 从一个点出发, 上下左右搜索看是否能找到相等于word的字符串. 因为每一次的dfs访问的点不能被二次访问, 所以要维护一个m * n 的boolean矩阵 记录访问过的点.
对于每一个点的dfs时间是O(m*n)。我们对每个顶点都要做一次搜索,所以总的时间复杂度最坏是O(m^2*n^2),空间上就是要用一个数组来记录访问情况,所以是O(m*n)

public class Solution {
    public boolean exist(char[][] board, String word) {
        if (word == null || word.length() == 0) {
            return true;
        }
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        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++) {
                if (helper(board, word, 0, i, j, used)) {
                    return true;
                }
            }
        }
        return false;
    }
    private boolean helper(char[][] board, String word, int index, int i, int j, boolean[][] used) {
        if (index == word.length()) {
            return true;
        }
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || used[i][j] || board[i][j] != word.charAt(index)) {
            return false;
        }
        used[i][j] = true;
        boolean res = helper(board, word, index + 1, i + 1, j, used) ||helper(board, word, index + 1, i - 1, j, used) || helper(board, word, index + 1, i, j + 1, used) || helper(board, word, index + 1, i, j - 1, used);
        used[i][j] = false;
        return res;
    }
}

没有评论:

发表评论