joj 1014 the matrix 从八个方向遍历访问矩阵

 

 1014: The Matrix


Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 2109 670 Standard

Given a matrix of characters, and a list of words, output whether or not each word is present in the matrix. Words may appear forwards and backwards. They may appear horizontally, vertically, and diagonally.

Input


The matrix, followed by a list of words. Only lower case characters will be used. Each matrix will be square, and contain no more than 20 characters on a side. The string XXX denotes the end of input.

Output


For each word, report whether or not it is present in the matrix. If it is present, output should read “<word> is in the matrix.” If it is not present, output should read “<word> is not in the matrix.”, where <word> is the word in question.

Sample Input

applexy
pxlhjke
edeqgfl
xocgvpl
gghnmnn
tahuupu
qdgbywb
apple
axe
apex
cat
car
hat
computer
gum
XXX

Sample Output

apple is in the matrix.
axe is in the matrix.
apex is in the matrix.
cat is not in the matrix.
car is not in the matrix.
hat is in the matrix.
computer is not in the matrix.
gum is in the matrix.

 

/*
	水题一个
	关键是找字符的时候
	沿着八个方向找
	但是每一次只能沿着一个方向遍历下去
*/
#include <stdio.h>
#include <string.h>
char matrix[21][21];
char str[21];
bool isIn(int row,int col)
{
	char tmp[21];
	memset(tmp,'\0',sizeof(tmp));
	tmp[0] = str[0];
	int var[2][8] = {{0,0,-1,1,1,-1,1,-1},
					{1,-1,0,0,-1,1,1,-1}};
	int curRow = 0,curCol = 0;
	for(int i=0;i<8;i++) //一共有八个方向
	{
		curRow = row;
		curCol = col;
		for(int j=1;j<strlen(str);j++) //一次只能沿着一个方向找
		{
			curRow += var[0][i];
			curCol += var[1][i];
			tmp[j] = matrix[curRow][curCol];
		}
		if(strcmp(tmp,str) == 0)
			return true;
	}
	return false;
}
int main()
{
	memset(matrix,'\0',sizeof(matrix));
	freopen("in.txt","r",stdin);
	scanf("%s",matrix[0]);
	for(int k=1;k<strlen(matrix[0]);k++)
		scanf("%s",matrix[k]);
	while(scanf("%s",str),strcmp(str,"XXX"))
	{
		bool flag = false;
		for(int i=0;i<strlen(matrix[0]);i++)
		{
			for(int j=0;j<strlen(matrix[0]);j++)
				if(matrix[i][j] == str[0])
					if(isIn(i,j))
					{
						flag = true;
						break;
					}
			if(flag)
				break;
		}
		if(flag)
			printf("%s is in the matrix.\n",str);
		else
			printf("%s is not in the matrix.\n",str);
	}
	fclose(stdin);
	return 0;
}

你可能感兴趣的:(apple,J#)