洛谷—P1101 单词方阵

在这里插入图片描述
需要记录方向的深度优先搜索

#include<iostream>
using namespace std;
char map[200][200];
bool visit[200][200];
int go[8][2] = { {1,1},{-1,-1},{-1,0},{0,-1},{1,0},{0,1},{1,-1},{-1,1} };
int pos[7][2];
const char str[] = "yizhong";
int n;
void dfs(int depth,int x,int y,int direct)
{
	if (depth == 7)
	{
		for (int i = 0; i < 7; ++i)
			visit[pos[i][0]][pos[i][1]] = true;
		return;
	}
	for (int i = 0; i < 8; ++i)
	{
		if (depth != 1 && i != direct) continue;
		int temp1 = x + go[i][0], temp2 = y + go[i][1];
		if (temp1>=0&&temp1<n&&temp2>=0&&temp2<n&&map[temp1][temp2] == str[depth])
		{
			//cout << "depth:" << depth << endl;
			//cout << temp1 << ',' << temp2 << ','<<map[temp1][temp2]<<endl;
			pos[depth][0] = temp1;
			pos[depth][1] = temp2;
			dfs(depth + 1, temp1, temp2,i);
		}
	}
}
int main()
{
	cin >> n;
	for (int i = 0; i < n; ++i)
		cin >> map[i];
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n; ++j)
			if (map[i][j] == 'y') {
				pos[0][0] = i;
				pos[0][1] = j;
				//cout << i << ',' << j << endl;
				dfs(1, i, j,-1);
			}
	for (int i = 0; i < n; ++i, cout << endl)
		for (int j = 0; j < n; ++j)
			if (visit[i][j])
				cout << map[i][j];
			else
				cout << '*';
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值