[华为机试真题]66.单词搜索

来源:互联网 发布:网络诈骗方式和种类 编辑:程序博客网 时间:2024/05/29 16:30

题目

这里写图片描述

代码

/*---------------------------------------*   日期:2015-07-06*   作者:SJF0115*   题目:WordSearch*   来源:华为机试真题-----------------------------------------*/#include <iostream>#include <string>#include <vector>#include <stack>#include <algorithm>using namespace std;bool DFS(vector<vector<char> > &board,string word,int index,int x,int y,vector<vector<bool> > &visited){    // 找到目标    if(index == word.size()){        return true;    }//if    int m = board.size();    if(m == 0){        return false;    }//if    int n = board[0].size();    // 出界    if(x < 0 || x >= m || y < 0 || y > n){        return false;    }//if    // 已访问过    if(visited[x][y]){        return false;    }//if    // 不相等 剪枝    if(board[x][y] != word[index]){        return false;    }//if    visited[x][y] = true;    // left    bool left = DFS(board,word,index+1,x,y-1,visited);    // right    bool right = DFS(board,word,index+1,x,y+1,visited);    // up    bool up = DFS(board,word,index+1,x-1,y,visited);    // bottom    bool bottom = DFS(board,word,index+1,x+1,y,visited);    visited[x][y] = false;    // 四个方向 任意方向找到一个即可    return left || right || up || bottom;}// 单词搜索bool WordSearch(vector<vector<char> > &board,int m,int n,string word){    if(n <= 0 || m <= 0 || board.empty()){        return false;    }//if    // 判断是否已经访问过    vector<vector<bool> > visited(m,vector<bool>(n,false));    // 搜索    for(int i = 0;i < m;++i){        for(int j = 0;j < n;++j){            if(board[i][j] == word[0]){                // 以board[i][j]为起点开始搜索                if(DFS(board,word,0,i,j,visited)){                    return true;                }//if            }//if        }//for    }//for    return false;}int main(){    int m,n;    string word;    //freopen("C:\\Users\\Administrator\\Desktop\\acm.txt","r",stdin);    while(cin>>m>>n>>word){        vector<vector<char> > board(m,vector<char>(n,0));        // 输入        for(int i = 0;i < m;++i){            for(int j = 0;j < n;++j){                cin>>board[i][j];            }//for        }//for        // 搜索        bool result = WordSearch(board,m,n,word);        if(result){            cout<<"YES"<<endl;        }//if        else{            cout<<"NO"<<endl;        }//else    }//while    return 0;}
0 0
原创粉丝点击