Word Search

对于我来说 这种dfs之类的题目还是挺有难度的,尤其是各种条件和设计要想清楚, dfs经典题目,尤其是最后要退一步,高亮处

public class Solution {
    public boolean exist(char[][] board, String word) {
        if(board==null|| board.length==0|| board[0].length==0) return false;
        if(word==null || word.length()==0) return true;
        int row = board.length, col = board[0].length;
        boolean [][] visit = new boolean [row][col];
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                if(helper(board,word,0,i,j,visit))
                    {return true;}
                else
                    continue;
            }
        }
        return false;
    }
    
    public boolean helper(char[][] b, String w, int wind, int r, int c, boolean [][] visit){
        if(wind==w.length()) return true;
        
        if(c<0||c>=b[0].length||r<0||r>=b.length) return false;
        if(visit[r][c]) return false;
        if(b[r][c]!=w.charAt(wind)) return false;
        
        visit[r][c]=true;
        if( helper(b,w,wind+1,r+1,c,visit)||helper(b,w,wind+1,r-1,c,visit)||helper(b,w,wind+1,r,c+1,visit)||helper(b,w,wind+1,r,c-1,visit)) return true;
        visit[r][c]=false; //if rt‘s value is not true, then r,c's position should not be occupied 
        return false;
    }
}

 

posted @ 2015-04-17 04:20  世界到处都是小星星  阅读(196)  评论(0编辑  收藏  举报