首页 > 代码库 > UVa 10010 - Where's Waldorf?

UVa 10010 - Where's Waldorf?

题目:给你一些单词和一个字母矩阵,问这个单词最早出现在哪里(单词可以向8个直线方向书写)。

分析:字符串。枚举矩阵中每个字母的8个方向,生成最长字符,然后在里面找单词即可。

说明:处理前,将大写字母先转化成小写字母。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

char text[52][52];
char word[20][52];
int  a[20],b[20];
int  dxy[8][2] = {1,0,0,1,-1,0,0,-1,1,1,1,-1,-1,1,-1,-1};

int cmp( char* a, char *b )
{
	for ( int i = 0 ; a[i] ; ++ i )
		if ( a[i] != b[i] )
			return 0;
	return 1;
}

void find_word( int n, int m, int l )
{
	memset( a, 0, sizeof(a) );
	memset( b, 0, sizeof(b) );
	
	char buf[52];
	for ( int i = 0 ; i < n ; ++ i )
	for ( int j = 0 ; j < m ; ++ j ) 
	for ( int k = 0 ; k < 8 ; ++ k ) {
		buf[0] = text[i][j];
		int xx = i,yy = j,count = 1;
		while ( 1 ) {
			xx += dxy[k][0];
			yy += dxy[k][1];
			if ( xx < 0 || xx >= n || yy < 0 || yy >= m )
				break;
			buf[count ++] = text[xx][yy];
		}
		buf[count] = 0;
		for ( int p = 0 ; p < l ; ++ p )
			if ( !a[p] && cmp( word[p], buf ) ) {
				a[p] = i+1;
				b[p] = j+1;
			}	
	}
	
	for ( int i = 0 ; i < l ; ++ i )
		printf("%d %d\n",a[i],b[i]);
}

int main()
{
	int T,n,m,l;
	while ( ~scanf("%d",&T) )
	while ( T -- ) {
		getchar();
		scanf("%d%d",&n,&m);
		for ( int i = 0 ; i < n ; ++ i )
			scanf("%s",text[i]);
		for ( int i = 0 ; i < n ; ++ i )
			for ( int j = 0 ; j < m ; ++ j )
				if ( text[i][j] >= 'A' && text[i][j] <= 'Z' )
					text[i][j] += 'a'-'A';
		scanf("%d",&l);
		for ( int i = 0 ; i < l ; ++ i )
			scanf("%s",word[i]);
		for ( int i = 0 ; i < l ; ++ i )
			for ( int j = 0 ; word[i][j] ; ++ j )
				if ( word[i][j] >= 'A' && word[i][j] <= 'Z' )
					word[i][j] += 'a'-'A';
		find_word( n, m, l );
		if ( T ) printf("\n");
	}
	return 0;
}