您的位置:首页 > 其它

hrbust 哈理工oj 1743 Word Search【DFS过】

2016-03-15 14:14 357 查看
Word Search
Time Limit: 1000 MSMemory Limit: 65535 K
Total Submit: 142(43 users)Total Accepted: 61(41 users)Rating:





Special Judge: No
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春季校赛 - 现场赛
Sample Input

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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息