hrbust 哈理工oj 1743 Word Search【DFS过】
2016-03-15 14:14
357 查看
Word Search | ||||||
| ||||||
Description | ||||||
There is a matrix only contains uppercase letters. Try to find a word in this matrix. You can go toward four directions (top, bottom, left, right), each position can only be visited once. | ||||||
Input | ||||||
There are multiple test cases. The first line is a positive integer T, indicating the number of test cases. For each test case, the first line contains three integer n, m, q. Then a matrix with size of n*m follows. After the matrix are q lines. Each line is a word with uppercase letters only. The length of each word is no more than 50. (1<=n, m <= 50,1 <= q <= 50) | ||||||
Output | ||||||
For each test, output q lines. If the word of ith line exists, print "Yes" in the ith line, else print "No". Output a blank line after each test case. | ||||||
Source | ||||||
哈理工2013春季校赛 - 现场赛 |
2
3 4 3
ABCE
SFCS
ADEE
ABCCED
SEE
ABCB
5 5 5
YYBDC
PMFNJ
KGJKD
HUAOP
JMUSB
MFMYBDCJN
BXIPOUCIMFVOHFNWO
KOAUMUSB
GJNNOB
CJC
Sample Output
Yes
Yes
No
No
No
Yes
No
No
这个题还是很容易T掉的一个题,最开始的思路是这样的:对于每一个字符串,如果能够在DFS过程中找到这条组成这个字符串的路径,标记上,然后输出YES,结果T了。。。。
原因很简单,如果图比较大的话,我们这样漫无目的的去搜是一定会T的,如果我们目的性明确的情况下去搜,必然就会节省很多时间。
正确思路是这样的:输入一个字符串,测出其长度,并且在图中找到字符串首字母,然后从首字母处出发DFS,找到的下一个位子要和字符串的第二个字母匹配上,然后进入下一层DFS,这层找到的下一个位子要和字符串的第三个字母匹配上,这样就会节省很多走了不该走的地方的时间。
第一发TLE,第二种思路(正确思路)17ms
AC代码:
#include<stdio.h> #include<string.h> using namespace std; int vis[55][55]; char a[55][55]; char bijiao[55]; char tmp[55]; int fx[4]={0,0,1,-1}; int fy[4]={1,-1,0,0}; int n,m; int len; int ok; void dfs(int x,int y,int cur) { if(ok==1)return ; if(cur==len) { ok=1; return ; } for(int i=0;i<4;i++) { int xx=x+fx[i]; int yy=y+fy[i]; if(xx>=0&&xx<n&&yy>=0&&yy<m&&vis[xx][yy]==0&&a[xx][yy]==tmp[cur]) { //printf("%d %d %c cur:%d\n",xx,yy,tmp[cur],cur); vis[xx][yy]=1; dfs(xx,yy,cur+1); vis[xx][yy]=0; } } } int main() { int t; scanf("%d",&t); while(t--) { int q; scanf("%d%d%d",&n,&m,&q); for(int i=0;i<n;i++) { scanf("%s",a[i]); } while(q--) { int x,y; scanf("%s",tmp); len=strlen(tmp); ok=0; memset(vis,0,sizeof(vis)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(a[i][j]==tmp[0]) { memset(vis,0,sizeof(vis)); vis[i][j]=1; dfs(i,j,1); } if(ok==1)break; } if(ok==1)break; } if(ok==1) { printf("Yes\n"); } else { printf("No\n"); } ok=0; } printf("\n"); } }
相关文章推荐
- 多种多样的App主界面Tab实现方法(一):Viewpager
- 数据类型
- 即时通讯常用第三方库
- dubbo
- Elasticsearch基础教程
- RecyclerView和ScrollView嵌套使用
- [转]如何处理iOS中照片的方向
- leetcode 54. Spiral Matrix
- 可视化的数据结构 - 各种算法动画演示
- c++构造函数
- Prohibited package name: java.stringDemo
- nginx http服务搭建配置
- What is a good buffer size for socket programming?
- Android设计模式之-观察着模式
- 机器学习之 EM算法
- HashMap实现原理分析
- easyui-tabs第一个标签被遮挡
- BSD(BSD,也称Berkeley Unix)Berkeley Software Distribution
- [bzoj2693&bzoj2194]Crash的数字表格&jzptab
- IOS学习 触摸和手势 手势识别器:单击、双击、轻扫、滑动、长按、旋转