LeetCod :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.

Example:

board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]

Given word = “ABCCED”, return true.
Given word = “SEE”, return true.
Given word = “ABCB”, return false.
代码
深度搜索即可。判断条件有点多。

class Solution {
    public boolean exist(char[][] board, String word) {
        if(board==null || board.length==0 || board[0].length==0 || word==null || word.length()==0) return false;
        
        int row=board.length, col=board[0].length;
        char[] wor = word.toCharArray();
        int[][] flag = new int[row][col];
        
        for(int i=0; i=board.length || col>=board[0].length || ind>=word.length || flag[row][col]==1 || board[row][col]!=word[ind]){
            return false;
        }
        // if(flag[row][col]==0 && board[row][col]==word[ind] && ind==word.length-1){
        if(ind==word.length-1){
            return true;
        }
        
        flag[row][col] = 1;
        boolean isc  =  search(board,flag,word,row-1,col,ind+1)||
                        search(board,flag,word,row+1,col,ind+1)||
                        search(board,flag,word,row,col-1,ind+1)||
                        search(board,flag,word,row,col+1,ind+1);
        flag[row][col] = 0;
        return isc;
        
    }
}

你可能感兴趣的:(LeetCode)