[华为机试真题]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
- [华为机试真题]66.单词搜索
- 单词搜索
- 单词搜索
- 单词搜索
- 单词博弈-华为OJ
- 华为中级【单词倒序】
- 华为笔试之最长单词
- 【华为oj】单词倒排
- 华为oj之兄弟单词
- 华为oj 单词倒排
- 【华为OJ】查找兄弟单词
- 【华为 OJ 】单词倒排
- 华为oj 单词倒排
- 单词统计(华为测试题目)
- 华为oj 查找兄弟单词
- 华为OJ:查找兄弟单词
- 华为OJ-查找兄弟单词
- 7.9 单词游戏 搜索
- Android错误之HAX is not installed on the machine(MAC OS)
- Codeforces Round #229 (Div. 2)B. Inna, Dima and Song
- ajax核心技术1---XMLHttpRequset对象的使用
- 招聘一个靠谱的 iOS Dever
- OC控件的代理方法步骤
- [华为机试真题]66.单词搜索
- 重写equals方法
- Struts2配置一个Action实现多个请求
- 设计模式
- Why Amazon Echo is the future of every home
- 开始
- matlab实现最短路径
- Ants - POJ 3565 KM算法
- 浅谈JavaWEB入门必备知识之Servlet入门案例详解