洛谷 P1443 马的遍历

该博客探讨了洛谷P1443编程题,涉及迷宫问题的最短路径算法。文章指出输出格式需要注意,要求左对齐并固定宽度为五个字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

迷宫的最短路径问题的翻版, 输出是个坑, 左对齐五个字符。

#include <iostream>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;

struct Coordinate{
	int row;
	int col;
};
const int MAX_SIZE = 400, INF = 2333333;
Coordinate start, goal;
//马的八个方向
Coordinate dir[8] = {{-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}}; 
char maze[MAX_SIZE + 1][MAX_SIZE + 1];
int dis[MAX_SIZE + 1][MAX_SIZE + 1];
int N, M;
queue<Coordinate> que;

void bfs()
{
	while (que.size()){
		Coordinate head = que.front();
		que.pop();
		for (int i = 0; i < 8; i++){
			Coordinate tmp;
			tmp.row = head.row + dir[i].row;
			tmp.col = head.col + dir[i].col;
			if (tmp.row >= 1 && tmp.row <=N && tmp.col >= 1 && tmp.col <= M &&
			 dis[tmp.row] [tmp.col] == INF){
				que.push(tmp);
				dis[tmp.row][tmp.col] = dis[head.row][head.col] + 1;
			}
		}
	}
}
int main()
{
	cin >> N >> M >> start.row >> start.col;
	for (int i = 1; i <= N; i++)
		for (int j = 1; j <= M; j++)
			dis[i][j] = INF;
	que.push(start);
	dis[start.row][start.col] = 0;
	bfs();
	for (int i = 1; i <= N; i++){
		for (int j = 1; j <= M; j++){
			if (dis[i][j] != INF){
				cout << left << setw(5) <<dis[i][j];
			}
			else {
				cout << left << setw(5) << -1;
			}
			if (j == M)
				cout << endl;
		}
	}		
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值