描述
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.
输入
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)
输出
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.
样例输入
2
3 4 3
ABCE
SFCS
ADEE
ABCCED
SEE
ABCB
5 5 5
YYBDC
PMFNJ
KGJKD
HUAOP
JMUSB
MFMYBDCJN
BXIPOUCIMFVOHFNWO
KOAUMUSB
GJNNOB
CJC
样例输出
Yes
Yes
No
No
No
Yes
No
No
题目大意:给出一个字符串在矩阵中是否能找到
解题思路:爆搜看看能不能从矩阵中找出这个字符串
#include <bits/stdc++.h> #define INF 0x3f3f3f3f using namespace std; const int N=100005; char M[55][55],vis[55][55]; int dir[4][2]={0,1,0,-1,1,0,-1,0}; int len,n,m,f; string s; void dfs(int x,int y,int pos) { if(pos==len-1) f=1; if(f==1||x>n||x<1||y>m||y<1) return; vis[x][y]=1; for(int i=0;i<4;i++){ int xx=x+dir[i][0]; int yy=y+dir[i][1]; if(s[pos+1]==M[xx][yy]&&vis[xx][yy]==0) dfs(xx,yy,pos+1); } vis[x][y]=0; } int main() { int k,T,q; cin>>T; while(T--){ cin>>n>>m>>q; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++) cin>>M[i][j]; } for(int i=1;i<=q;i++){ cin>>s; f=0; len=s.size(); for(int a=1;a<=n;a++){ for(int b=1;b<=m;b++){ if(M[a][b]==s[0]) dfs(a,b,0); } } if(f) cout<<"Yes "; else cout<<"No "; } cout<<" "; } }