您的位置:首页 > 编程语言

leetcode-Word Search(2014.2.18)

2014-04-13 22:01 274 查看
递归回溯,采用深度优先搜索的方法:

class Solution {
public:
    bool flag=false;
    bool visited[250][250];
    bool exist(vector<vector<char>> &board, string word) {
        if(word.length()==0) return true;
        int m=board.size();
        int n=board[0].size();
        if(board.size()==0) return true;
        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                visited[i][i]=false;
            }
        }
        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(flag==true) return true;
                if(flag==false) DFS(i,j,board,word);
                }
            }   
            return flag;
        }
        
       void DFS(int x,int y,vector<vector<char>> &board,string word){
            if(x<0||y<0||x>=board.size()||y>=board[0].size())
                return;
            if(word.length()==0){
                flag=true;
                return;
            }
            if(flag==true) return;
            if(visited[x][y]==true) return;
            
            if(board[x][y]==word.at(0)){
                visited[x][y]=true;
                if(word.length()==1){//若此处无判定,board只有一个元素的时候,便会出错
                flag=true;
                return;
            }
                DFS(x+1,y,board,word.substr(1));
                DFS(x,y+1,board,word.substr(1));
                DFS(x,y-1,board,word.substr(1));
                DFS(x-1,y,board,word.substr(1));
                visited[x][y]=false;
            }
        }
    };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 编程