Word Search(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.ui

For example, Given board =code

[ ['A','B','C','E']
['S','F','C','S'],
['A','D','E','E'] ]递归

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

思路:使用dfs. 先在矩阵中找到word0],若找到,就执行helper函数继续查找。递归结束条件是 index == word.length(); 若是是超过边界或者board[i != word.charAt(index) 就return false。 为防止same letter cell may be used more than once, 要标记已经访问过的letter为 #. 每次递归结束之后还要还原以防影响下一次。io

时间复杂度: mn4^(k-1). 也就是mn4^k.
m X n is board size, k is word size.
(脑补题目为从一个字符矩阵中搜索某个字符串是否存在,能够向四个方向延伸。那么dfs和bfs的时间复杂度是指数级别的,大概是4的字符串长度次方,由于每次均可能走四个方向(实际上比这个低,由于不必定四个方向均可以走,也可能走过的地方不能走,可是给出最坏状况就能够了))
空间复杂度: recuision最深是k层,recursive部分空间复杂度应该是O(k)class

public class Solution {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    if (helper(i, j, 0, word,board) == true) {
                        return true;
                    }
                }
            }
            
        }
        return false;
    }
    
    private boolean helper(int i, int j, int index, String word, char[][] board) {
        if (index == word.length()) {
            return true;
        }
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index)) {
            return false;
        }
        char tmp = board[i][j];
        board[i][j] = '#';
        
        boolean rst = helper(i + 1, j, index + 1, word, board) || helper(i, j + 1, index + 1, word, board) || helper(i, j - 1, index + 1, word, board) || helper(i - 1, j, index + 1, word, board);
        
        board[i][j] = tmp;
        return rst;
    }
}
相关文章
相关标签/搜索