【洛谷】P1101 单词方阵(字符串、搜索)

题目:https://www.luogu.org/problem/P1101

标签:字符串、搜索

【题解】

主要思路就是当遇到 ‘y’ 后,再从八个方向开始搜索。从某个方向开始搜索时,如果满足条件就递归,否则结束递归。当 “yizhong” 字符串成功搜索到时,用result数组保存路径,此次dfs也就结束了。

注意: 用 string 容器存储时,一定要判断下标越界问题。

【代码】

#include <iostream>
#include <string>
using namespace std;
//dir是八个方向,fdir是dir的对应反方向。
int n, dir[8][2] = { {-1,-1},{0,-1},{1,-1},{-1,0},{1,0},{-1,1},{0,1},{1,1} };
int fdir[8][2] = { {1,1},{0,1},{-1,1},{1,0},{-1,0},{1,-1},{0,-1},{-1,-1} };
char ch[200][200];	//输入存储阵列
string cmp = "yizhong";
int result[200][200];	//结果,0表示输出"*",1表示输出原数(表示成功找到)

void dfs(int x,int y,int k,int ans)
{
	if (ans == 6) {	//ans==6,成功找到"yizhong"
		for (int i = 0; i < 7; i++)	//把"yizhong"字符串的坐标用result数组置为1
		{
			result[x][y] = 1;
			//利用fdir反向找路径
			x += fdir[k][0];
			y += fdir[k][1];
		}
		return;
	}
	else {
		x += dir[k][0];
		y += dir[k][1];
		if (x < 0 || y < 0 || x >= n || y >= n)	return;	//越界
		ans++;
		if (ch[x][y] == cmp[ans])	//比较,相等就继续往下找
			dfs(x, y, k, ans);
	}
}

int main()
{
	cin >> n;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			cin >> ch[i][j];

	for (int i = 0; i < n; i++)	//从每个点开始找
		for (int j = 0; j < n; j++)
		{
			if (ch[i][j] == 'y') {	//找到'y',从八个方向开始搜索
				for (int k = 0; k < 8; k++)
					dfs(i, j, k, 0);
			}	
		}

	for (int i = 0; i < n; i++)	//输出
	{
		for (int j = 0; j < n; j++)
			if (result[i][j])	cout << ch[i][j];
			else    cout << "*";
		cout << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值