Word Search

来源:互联网 发布:淘宝客服中心怎么设置 编辑:程序博客网 时间:2024/06/14 11:22
这道题是典型的回退算法,类似于树中的DFS算法,关键在于递归算法框架的构成。
public class WordSearch {    public boolean exist(char[][] board, String word) {        int row = board.length;        int col = board[0].length;        for (int i=0;i<row;i++){            for (int j=0;j<col;j++){                if (board[i][j]!=word.charAt(0)){                    continue;                }else{                    board[i][j] = 1;                    if (helper(board,i,j,word,0)){                        return true;                    }else {                        board[i][j] = word.charAt(0);                        continue;                    }                }            }        }        return false;    }    private static boolean helper(char[][] board,int r,int c,String word,int step){        if (step==word.length()) return true;        if (r-1>=0&&board[r-1][c]==word.charAt(step+1)){            board[r-1][c] = 1;            if (helper(board,r-1,c,word,step+1)) return true;            board[r-1][c] = word.charAt(step+1);        }        if (c+1<board[0].length&&board[r][c+1]==word.charAt(step+1)){            board[r][c+1] = 1;            if (helper(board,r,c+1,word,step+1)) return true;            board[r][c+1] = word.charAt(step+1);        }        if (r+1<board.length&&board[r+1][c]==word.charAt(step+1)){            board[r+1][c] = 1;            if (helper(board,r+1,c,word,step+1)) return true;            board[r+1][c] = word.charAt(step+1);        }        if (c-1>=0&&board[r][c-1]==word.charAt(step+1)){            board[r][c-1] = 1;            if (helper(board,r,c-1,word,step+1)) return true;            board[r][c-1] = word.charAt(step+1);        }        return false;    }}

0 0