NEUQ-ACM预备队week4-搜索

P1605 迷宫

题目

在这里插入图片描述

思路

使用深度优先搜索算法,用一个ans存储达到终点的次数,并且因为要统计全部的达到终点的次数,所以在标记已经遍历过的节点,回溯后需要清除标记以确保能够搜索全部的情况

代码实现

#include<iostream>
using namespace std;
int n, m, t;
int sx, sy, fx, fy;
int map[6][6]={0};
//false表没有走过 true表示已经走过了
//检查地图是否已经走过,因为我们不可以反复在两个点处横跳
//同时,如果把没有走过记录为false,在后续进行if判断的时候
//可以直接把true作为不能走的条件,作为bool型可以直接
//在if中写入mapcheck[tox][toy]中
bool mapcheck[6][6] = { false };
//打表,记录四个行走方向-前后左右
int xc[4] = { 0,0,1,-1 };
int yc[4] = { -1,1,0,0 };
int ans = 0;
void DFS(int x,int y)
{
  //达到目标态 结束回溯
	if (x == fx && y == fy)
	{
		ans++;
		return;
	}
	else
	{
		for (int i = 0; i < 4; i++)
		{
			int tox = x + xc[i];
			int toy = y + yc[i];
			//超出边界,已经走过,有障碍不能走
			if (tox<1 || toy<1 || tox>n || toy>m || mapcheck[tox][toy] || map[tox][toy] == 1)
			{
				continue;
			}
			//可以走就继续DFS
			else
			{
				//同时注意清除标记--因为要检索全部的情况~
				mapcheck[x][y] = true;
				DFS(tox, toy);
				mapcheck[x][y] = false;
			}
		}
	}
}
int main()
{
	cin >> n >> m >> t;
	cin >> sx >> sy >> fx >> fy;
	while (t--)
	{
		int a, b;
		cin >> a >> b;
		//1是山脉不能走~
		map[a][b] = 1;
	}
	DFS(sx, sy);
	cout << ans;
	return 0;
}

P1443 马的遍历

题目

在这里插入图片描述

思路

利用广度优先搜索,首先,根据BFS搜索的特性,我们可以将第一个节点延伸出的所有结点都记录为1,也就是步数,所以我们只需要用BFS尽量遍历全图,将每个点的步数记录为上一个点用的步数加一,最后判断一下步数为0的点,因为我们有两种情况步数是零,第一种是走不到,第二种是初始点,走不到输出-1,初始点正常输出0,就好啦~

代码实现

#include<iostream>
#include<queue>
using namespace std;
int map[405][405];
bool mapcheck[405][405];
int sx[8] = {-2,2,-2,2,1,1,-1,-1};
int sy[8] = { 1,1,-1,-1,-2,2,-2,2 };
int n, m, x, y;
struct point {
	int x, y;
	int step;
};
queue<point>que;
int main()
{
  //qwq临近作业提交时间,这个代码写的比较差
  //后期还可以优化~hhhc什么鬼point a.x a.y a.step,
  //大概可以直接用队列的首元素值,不用额外记录a
	cin >> n >> m >> x >> y;
	point a;
	a.x = x;
	a.y = y;
	a.step = 0;
	que.push(a);
	int nx = que.front().x;
	int ny = que.front().y;
	map[nx][ny] = que.front().step;
	mapcheck[nx][ny] = true;
	while (!que.empty())
	{
		nx = que.front().x;
		ny = que.front().y;
		int step= que.front().step;
		que.pop();
		for (int i = 0; i < 8; i++)
		{
			int nextx = nx + sx[i];
			int nexty = ny + sy[i];
			if (nextx >= 1 && nextx <= n && nexty >= 1 && nexty <= m && !mapcheck[nextx][nexty])
			{
				a.x = nextx;
				a.y = nexty;
				a.step = step + 1;
				map[nextx][nexty] = step+1;
				mapcheck[nextx][nexty] = true;
				que.push(a);
			}
		}		
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= m; j++)
		{
			if (i == x && j == y && map[i][j] == 0)
				printf("%d ", map[i][j]);
			else if (map[i][j] == 0)
			{
				printf("-1 ");
			}
			else 
			printf("%d ", map[i][j]);
		}
		printf("\n");
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值