Maze 解题报告
Maze
Description
You are given a special Maze described as an n*m matrix, please find the shortest path to reach (n,m) from (1,1);
Input
The first line of the input is an integer T (T <= 100), which stands for the number of test cases you need to solve.
Each test case begins with two integers n, m (1 <= n, m <= 250) in the first line indicating the size of the board. Then n lines follow, each line contains m numbers either 0 or 1 which are:
0 : represents a grid on which you can step.
1 : represents a wall.
Output
For every test case, you should output "Case #k: " first, where k indicates the case number and starts at 1. If it’s impossible to reach the end position, just output “-1”. Otherwise, output the minimum number of steps to solve this problem.
Sample Input
1
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
Case #1: 8
这题据说是2011 UESTC Training for Search Algorithm——A,不过我找不到原题,所以不知道自己写的能不能过。觉得该题是最好的BFS入门题啦。
这是我第一次写BFS,纪念一下^_^
题目意思就是找出从点(1, 1) 到 点(n, m) 的距离最短是多少。注意格子是 0 的点才能走,1代表墙,是不能走的。
因为BFS 是逐层拓展的,不像DFS 一直往深处找,所以能保证当达到点(n, m) 时即找到最短的距离。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std; const int maxn = + ;
struct node
{
int x;
int y;
int step;
};
int maze[maxn][maxn];
int dx[] = {, , , -};
int dy[] = {, , -, }; int main()
{
int T, n, m;
while (scanf("%d", &T) != EOF)
{
for (int cas = ; cas <= T; cas++)
{
scanf("%d%d", &n, &m);
for (int i = ; i <= n; i++)
{
for (int j = ; j <= m; j++)
scanf("%d", &maze[i][j]);
}
int ans = ;
queue<node> q;
q.push({, , }); // 代表从坐标点(1, 1)出发
while (!q.empty())
{
node cur = q.front(); // 取出队首元素
q.pop();
int cur_x = cur.x;
int cur_y = cur.y;
if (cur_x == n && cur_y == m) // 到达目标节点
{
ans = cur.step; // 得到最短步数
break;
}
for (int i = ; i < ; i++)
{
int tx = cur_x + dx[i];
int ty = cur_y + dy[i];
if (tx >= && tx <= n && ty >= && ty <= m && !maze[tx][ty]) // 可以走且没有走过
{
maze[tx][ty] = ;
q.push({tx, ty, cur.step+});
}
}
}
printf("Case #%d: %d\n", cas, ans);
}
}
return ;
}
最新文章
- Reactjs的Controller View模式
- 那些年,我们一起疯狂的C#
- iOS UIWebView中javascript与Objective-C交互、获取摄像头
- MySQL数据库主键设计原则
- 5 echo展开
- Java将一段逗号分割的字符串转换成一个数组
- tomcat服务器不输出访问日志
- 第三章TP-Link 703N OpenWrt设置网络
- 如何在Java中定义常量(Constant)
- POJ1840: Eqs(hash问题)
- iOS 更好用的打Log方式-显示文件名、行数
- TextView drawablePadding没有效果
- jq商品展示图放大镜 and 原生js和html5写的放大镜效果 ~~效果不错
- Java核心技术-高级特性(2)- SoftReference, WeakReference and PhantomReference
- centos下美团sql优化工具SQLAdvisor的安装
- jq实现数字增加或者减少的动画
- DIV内文字两端对齐
- Apache shiro如何实现一个账户同一时刻只有一个人登录
- Weex是如何让JS调用产生原生UIView的?
- MP实战系列(二)之集成swagger
热门文章
- Python入门--4--分之和循环
- go1.11新特性,mark一下
- 关于整合spring+mybatis 第三种方式-使用注解
- Java游戏服务器搭建
- Chrome V8系列--浅析Chrome V8引擎中的垃圾回收机制和内存泄露优化策略
- WebGIS开发之用openlayers加载离线百度地图
- Java中Class.this和this的区别(转)
- spring启动时加载字典表数据放入map
- Hijacking FM Radio with a Raspberry Pi &; Wire
- [Cypress] install, configure, and script Cypress for JavaScript web applications -- part1