leetcode(79)单词搜索

单词搜索

解题思路:递归+dfs+回溯

class Solution {
    public boolean exist(char[][] board, String word) {
        int xlen = board.length;
        int ylen = board[0].length;
        int slen = word.length();
        int t = 0;
        boolean[][] flags = new boolean[xlen][ylen];
        for(int i=0;i<xlen;++i){
            for(int j=0;j<ylen;++j){
                if(validate(board,xlen,ylen,slen,i,j,word,flags,0)){
                    return true;
                }
                for(int m=0;m<xlen;++m){
                    for(int n=0;n<ylen;++n){
                        if(flags[m][n]){
                            flags[m][n]=false;
                        }
                    }
                }
            }
        }
        return false;
    }
    public boolean validate(char[][] board,int xlen,int ylen, int slen, int i, int j, String word, boolean[][] flags,int t){
        if(t==slen){
            return true;
        }
        if(i<0||i>=xlen||j<0||j>=ylen){
            return false;
        }
        if(flags[i][j]==false&&board[i][j]==word.charAt(t)){
            flags[i][j] = true;
            if(validate(board,xlen,ylen,slen,i-1,j,word,flags,t+1)||
            validate(board,xlen,ylen,slen,i,j-1,word,flags,t+1)||
            validate(board,xlen,ylen,slen,i+1,j,word,flags,t+1)||
            validate(board,xlen,ylen,slen,i,j+1,word,flags,t+1)){
                return true;
            }
            flags[i][j]=false;
        }
        return false;
        
    }
}

 

posted @ 2019-08-02 16:51  海平面下的我们  阅读(113)  评论(0编辑  收藏  举报