7084:迷宫问题

本文介绍了一种使用BFS(广度优先搜索)算法解决迷宫问题的方法,结合C++代码实现。通过字符串记录路径,并利用队列进行搜索。文章探讨了在解决问题过程中遇到的知识盲区,并分享了做题经验和新学到的技术点,包括如何判断位置合法性、更新已访问状态等。
摘要由CSDN通过智能技术生成

7084:迷宫问题

题目链接http://noi.openjudge.cn/ch0205/7084/

思路 :BFS+queue,用string 记录走的方向,然后溯源。
这道题真的是花了我很多时间,题目很基础,不难,但是找到自己很多知识盲区。然后自己的收获写在另外一篇文章中,有一些做题注意事项,以及新的知识点链接https://blog.csdn.net/weixin_46028214/article/details/114031981

#include<iostream>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
char a[10][10];
int fx[4][2] = { {1,0},{-1,0} ,{0,-1},{0,1} };
typedef struct Node {
	Node(string ss, int xx, int yy) :s(ss), x(xx), y(yy) {}
	string s;
	int x, y;
}node;
queue<node> q;
bool visited[10][10];
string str;
bool pd(int x, int y) {//注意
	return x >= 0 && x < 5 && y >= 0 && y < 5;
}
void bfs() {
	while (!q.empty()) {
		node temp = q.front();
		q.pop();
		if (temp.x == 4 && temp.y == 4) {
			str = temp.s;
			break;
		}
		for (int i = 0; i < 4; i++) {
			int x = temp.x + fx[i][0], y = temp.y + fx[i][1];
			if (pd(x,y)&&!visited[x][y] && a[x][y] == '0') {
				visited[x][y] = 1;
				q.push(node(temp.s + to_string(i), x, y));
			}
		}
	}
}
int main() {
	for (int i = 0; i < 5; i++) {
		for (int j = 0; j < 5; j++) {
			cin >> a[i][j];
		}
	}
	q.push(node("", 0, 0));
	memset(visited, 0, sizeof(visited));
	visited[0][0] = 1;
	bfs();
	int x = 0, y = 0;
	printf("(0, 0)\n");
	for (int i = 0; i < str.size(); i++) {
		x += fx[str[i]-'0'][0], y += fx[str[i]-'0'][1];//注意
		printf("(%d, %d)\n", x, y);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值