迷宫寻宝路线

题目描述

小码君是一名游戏开发者,他正在开发一个基于二维 n×n 的迷宫游戏。

他需要编写一个算法:从游戏地图的左上角开始进行搜索,并按搜索上下左右的顺序输出所有经过的格子上的数字,以确保所有格子都被搜索到。

这些数字代表了游戏中的关键信息,例如宝藏位置、怪物位置、陷阱位置等。通过这个算法,可以帮助玩家找到所有的宝藏并击败所有的怪物,顺利通过迷宫。

输入格式

输入一个整数 n 表示数字迷宫阵列为n∗n

下一行开始,共 n 行,每行 n 个数字

输出格式

共 n∗n 个整数,每两个整数之间用一个空格隔开,顺序是搜索的顺序

样例输入

4
1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6

样例输出

1 5 2 9 6 3 3 0 7 4 4 1 8 5 2 6

样例输入

5
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5

样例输出

1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 5 4 3 2 5 4 3 5 4 5

说明提示

n 不超过 100

参考代码

#include
using namespace std;
const int N = 105;
struct node{
	int x, y, step;
};
queue q;
int dir[4][2] = {1, 0, 0, 1, 0, -1, -1, 0};
int n, maps[N][N];
bool vis[N][N]; // 标记数组 
void bfs(){
	//1 起点入队列 
	q.push({1, 1, 0});
	vis[1][1] = true;
	//2 取出队头,出队
	while(q.size()){
		node nd = q.front();
		q.pop();
		int x = nd.x;
		int y = nd.y;
		cout << maps[x][y] << " ";
		for(int i=0; i<4; i++){
			int nx = x + dir[i][0];
			int ny = y + dir[i][1];
			if(maps[nx][ny] == -1 || vis[nx][ny]) continue;
			q.push({nx, ny, nd.step+1});
			vis[nx][ny] = true;
		}
	} 
	//3 终点 / 无解 
}
int main(){
	cin>>n;
	memset(maps, -1, sizeof maps); // -1表示墙 
	for(int i=1; i<=n; i++){
		for(int j=1; j<=n; j++){
			cin>>maps[i][j];
		}
	}
	bfs();

	return 0;
}

你可能感兴趣的:(C++,NOIP普及组,算法,c++,图论)