单词方阵

单词方阵

  • 搜索. 按方向 \(dfs\) 即可
  • 每次搜索前要清除标记
#include <cstdio>
#include <cctype>
#include <cstring>
const int MAXN=100+1;
const int dx[8]={-1,1,0,0,-1,1,-1,1};
const int dy[8]={0,0,-1,1,-1,-1,1,1};
const char s[]="yizhong";
int mtr[MAXN][MAXN];
bool chos[MAXN][MAXN];
inline char read()
{
	char c=getchar();
	while(!isalpha(c))c=getchar();
	return c;
}
void dfs(int x,int y,int k,int i,bool& is,int n){
	if(mtr[x][y] != s[i])return;
	if(i==6){
		is=true;
		chos[x][y]=true;
		return;
	}
	int a=x+dx[k],b=y+dy[k];
	if(a>=0 && a<n && b>=0 && b<n)dfs(a,b,k,i+1,is,n);
	if(is)chos[x][y]=true;
}
int main()
{
	memset(mtr,0,sizeof(mtr));
	memset(chos,0,sizeof(chos));
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)mtr[i][j]=read();
	for(int i=0;i<n;i++)
		for(int j=0;j<n;j++)
			if(mtr[i][j]=='y')
			{
				bool is=false;
				for(int k=0;k<8;k++){
					is=false;
					dfs(i,j,k,0,is,n);
				}
			}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)putchar(chos[i][j]?mtr[i][j]:'*');
		if(i!=n-1)putchar('\n');
	}
	return 0;
}
posted @ 2018-07-14 07:11  昤昽  阅读(152)  评论(0编辑  收藏  举报