week2 作业A - Maze

题意

东东有一张地图,想通过地图找到妹纸。地图显示,0表示可以走,1表示不可以走,左上角是入口,右下角是妹纸,这两个位置保证为0。既然已经知道了地图,那么东东找到妹纸就不难了,请你编一个程序,写出东东找到妹纸的最短路线。

input

输入是一个5 × 5的二维数组,仅由0、1两数字组成,表示法阵地图。

output

输出若干行,表示从左上角到右下角的最短路径依次经过的坐标,格式如样例所示。数据保证有唯一解。

sample input

0 1 0 0 0
0 1 0 1 0
0 1 0 1 0
0 0 0 1 0
0 1 0 1 0

sample output

(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(2, 2)
(1, 2)
(0, 2)
(0, 3)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

思路

总结

代码

#include<cstdio>
#include<iostream>
#include<string>
#include<cmath>
#include<cstdlib>
#include<queue>
using namespace std;
struct point
{
	int x,
		y;
};
int map[5][5];
point route[5][5];
const int x2[4] = { +1,-1,0,0 };
const int y2[4] = { 0,0,+1,-1 };
void r(point);
int main()
{
	queue<point> q;
	for (int j = 0; j < 5; j++)
		for (int i = 0; i < 5; i++)
			cin >> map[j][i];
	point p1;
	p1.x = 0;
	p1.y = 0;
	q.push(p1);
	while (!q.empty())
	{
		point head = q.front(), temp;
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			temp.x = x2[i] + head.x;
			temp.y = y2[i] + head.y;
			if (temp.x < 0 || temp.y < 0 ||temp.x > 4 || temp.y > 4|| map[temp.x][temp.y] == 1 || map[temp.x][temp.y] == 2)
				continue;
			map[temp.x][temp.y] = 2;
			route[temp.x][temp.y] = head;
			q.push(temp);
		}
	}
	point p2;
	p2.x = 4;
	p2.y = 4;
	r(p2);
	return 0;
}
void r(point p)
{
	if (p.x != 0 || p.y != 0)
		r(route[p.x][p.y]);
	if(p.x!=4||p.y!=4)
		printf("(%d, %d)\n", p.x, p.y);
	else
	printf("(%d, %d)", p.x, p.y);
	return;
}

week2 作业B - Pour Water

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值