题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1743
Word Search
Time Limit: 1000 MS Memory Limit: 65535 K
Total Submit: 157(56 users) Total Accepted: 74(53 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.
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
【中文题意】给你n行m列字符,下面有q个询问,问你在这n行m列字符中能不能找到某一串连续的字符。
【思路分析】先判断第i行第j列的字符是不是等于这一串字符的首个字符,如果等于的话就从这个字符开始深搜。
【AC代码】
#include<cstdio>
#include<cstring>
#include<map>
#include<cmath>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
char a[55][55];
char str[106];
int t,n,m,q,len;
int book[55][55];
int maxn=0;
void dfs(int x,int y,int l)
{
if(l==len-1)
{
if(str[l]==a[x][y])
{
maxn=1;
}
return ;
}
else
{
if(a[x][y]==str[l])
{
int xx,yy;
for(int i=0; i<4; i++)
{
xx=x+dir[i][0];
yy=y+dir[i][1];
if(xx>=0&&xx<n&&yy>=0&&yy<m&&book[xx][yy]==0&&a[xx][yy]==str[l+1])
{
//printf("%d %d+++\n",xx,yy);
book[xx][yy]=1;
dfs(xx,yy,l+1);
book[xx][yy]=0;
}
}
}
else
{
return ;
}
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&q);
for(int i=0; i<n; i++)
{
scanf("%s",&a[i]);
}
for(int i=1; i<=q; i++)
{
maxn=0;
scanf("%s",str);
len=strlen(str);
int flag=0;
for(int j=0; j<n; j++)
{
for(int k=0; k<m; k++)
{
if(a[j][k]==str[0])
{
memset(book,0,sizeof(book));
book[j][k]=1;
dfs(j,k,0);
if(maxn)
{
flag=1;
break;
}
}
}
if(flag)break;
}
if(flag)
printf("Yes\n");
else
printf("No\n");
}
printf("\n");
}
return 0;
}