第五次训练H题

问题链接:Problem H

问题简述:

给出一幅5*5的地图,1表示墙壁,0表示道路,输出由坐上角到右下角的最短路径。
问题分析:

最短路径问题,可用BFS解决。难点在于如何输出路径。

程序说明:

在结构中定义了一个二维数组,用于存储每一步行走的坐标,用于结果输出路径。坑点在于格式问题“,”后有一个空格。

AC通过的C语言程序如下:

#include<iostream>
#include<cstdio>
#include<cstdlib> 
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
int map[6][6];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
bool vis[6][6];
struct node{
	int x;
	int y;
	int route[50][2];
	int step;
};
void init(){
	memset(map,0,sizeof(map));
	memset(vis,0,sizeof(vis));
}
bool edge(int x,int y){
	if(x>=0&&y>=0&&x<5&&y<5&&map[x][y]==0&&vis[x][y]==0){
		return 1;
	}
	else
		return 0;
}
node BFS(){
	queue<node>q;
	node p1;
	p1.x=0;
	p1.y=0;
	p1.step=0;
	p1.route[0][0]=0;
	p1.route[0][1]=0;
	vis[0][0]=1;
	q.push(p1);
	while(!q.empty()){
		node p2=q.front();
		q.pop();
		if(p2.x==4&&p2.y==4){
			return p2;
		}
		for(int i=0;i<4;i++){
			int next_x=p2.x+dir[i][0];
			int next_y=p2.y+dir[i][1];
			if(edge(next_x,next_y)){
				p1=p2;
				p1.x=next_x;
				p1.y=next_y;
				p1.step=p2.step+1;
				p1.route[p1.step][0]=next_x;
				p1.route[p1.step][1]=next_y;
				vis[next_x][next_y]=1;
				q.push(p1);
			}
		}
	}
}
int main(){
	std::ios::sync_with_stdio(false);
	init();
	for(int i=0;i<5;i++){
		for(int j=0;j<5;j++){
			cin>>map[i][j];
		}
	}
	node ans=BFS();
	for(int i=0;i<=ans.step;i++){
		cout<<"("<<ans.route[i][0]<<", "<<ans.route[i][1]<<")"<<endl;
	}
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值