UVA10010 Where's Waldorf?

链接: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;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值