鏈接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=951
因爲最近在刷劉汝佳的白書入門,所以基本開始做的都是UVA上的題目,是從基礎的開始刷的,想要打好基礎的,不要爲以後留遺憾。。
題意:這道題是給你一個N*M的字母矩陣,然後再給出一個字符串,讓在矩陣中找出這個字符串,可以從8個方向找(上,下,左,右,左上,左下,右上,右下),一旦選擇了一個方向,只能就是一直這個方向,不能字符串的前半部分是向右,後半部分是向下。。同時,大小寫視爲同一種,所以先用了toupper()函數將所有的字母都改成了大寫,這樣便於比較。最後還有一點就是,在你的每組矩陣輸完之後有個空行,最後一個沒有。。
代碼:
#include<cstdio>
#include<cctype>
#include<cstring>
using namespace std;
char word[25],a[55][55];
bool search(int s,int d,int n,int m,int j)
{
int x,y;
x=s;y=d;
int count=0;
while(x<n&&a[x][y]==word[count]&&count<j)//向右搜索
{
x++;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(x>=0&&a[x][y]==word[count]&&count<j) //向左搜索
{
x--;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(y>=0&&a[x][y]==word[count]&&count<j)//向上搜索
{
y--;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(y<m&&a[x][y]==word[count]&&count<j)//向下搜索
{
y++;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(x<n&&y>=0&&a[x][y]==word[count]&&count<j)//向右上方向搜索
{
x++;
y--;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(x<n&&y<m&&a[x][y]==word[count]&&count<j)//向右下方向搜索
{
x++;
y++;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(x>=0&&y>=0&&a[x][y]==word[count]&&count<j)//向左上方向搜索
{
x--;
y--;
count++;
}
if(count==j)
return true;
x=s;y=d;count=0;
while(x>=0&&y<m&&a[x][y]==word[count]&&count<j)//向左下方向搜索
{
x--;
y++;
count++;
}
if(count==j)
return true;
return false;
}
int main()
{
int t,n,m,i,j,x,y,z;
scanf("%d",&t);
for(int k=0;k<t;k++)
{
scanf("%d%d",&n,&m);
getchar();
for(i=0;i<n;i++)
gets(a[i]);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
a[i][j]=toupper(a[i][j]);
scanf("%d",&z);
getchar();
for(i=0;i<z;i++)
{
gets(word);
for(j=0;word[j]!='\0';j++)
word[j]=toupper(word[j]);
int flag=0,s,d;
for( s=0;s<n;s++)
{
for( d=0;d<m;d++)
if(a[s][d]==word[0])
{
if(search(s,d,n,m,j))
{
flag=1;
printf("%d %d\n",s+1,d+1);
break;
}
}
if(flag==1)
break;
}
}
if(k<t-1)
printf("\n");
}
return 0;
}