最少步数
来源:互联网 发布:诲女知之乎的语气 编辑:程序博客网 时间:2024/05/22 17:27
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
- 输入
- 第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。 - 输出
- 输出最少走几步。
- 样例输入
23 1 5 73 1 6 7
- 样例输出
1211
#include <iostream>#include<queue>#include<cstring>const int dx[4] = {0, 0,-1, 1};const int dy[4] = {-1,1, 0, 0};struct node{ int x, y; int step;};node now, next;node S,E;using namespace std;bool vis[10][10];int map[9][9] = {1,1,1,1,1,1,1,1,1, 1,0,0,1,0,0,1,0,1 ,1,0,0,1,1,0,0,0,1 ,1,0,1,0,1,1,0,1,1 ,1,0,0,0,0,1,0,0,1 ,1,1,0,1,0,1,0,0,1 ,1,1,0,1,0,1,0,0,1 ,1,1,0,1,0,0,0,0,1 ,1,1,1,1,1,1,1,1,1};int bfs(){ if(S.x == E.x && S.y == E.y) return 0; memset(vis, false,sizeof(vis)); queue<node>q; q.push(S); vis[S.x][S.y] = true; while(!q.empty()) { now = q.front(); q.pop(); for(int i=0; i<4; i++) { next.x = now.x + dx[i]; next.y = now.y + dy[i]; next.step = now.step + 1; if(map[next.x][next.y] == 1||next.x > 9 || next.x<0 || next.y>9 || next.y<0 || vis[next.x][next.y]) continue; vis[next.x][next.y] = true; q.push(next); if(next.x == E.x && next.y == E.y) return next.step; } } return -1;}int main(){ int T; int x1, y1, x2, y2; cin >> T; while(T--) { cin >> x1 >> y1; cin >> x2 >> y2; S.x = x1; S.y = y1; S.step = 0; E.x = x2; E.y = y2; int ans = bfs(); if(ans >= 0) cout << ans << endl; } return 0;}
0 0
- 最少步数
- 最少步数
- NYOJ 最少步数
- nyoj58 最少步数
- NYOJ58-最少步数
- 最少步数
- 最少步数
- 58 最少步数
- nyoj58最少步数
- NYOJ_58 最少步数
- nyoj58最少步数
- nyoj58最少步数
- nyoj 最少步数
- 最少步数BFS
- ACM58最少步数
- NYOJ【最少步数】
- 最少步数
- nyoj58 最少步数
- jQuery的deferred对象详解
- Service和Thread的关系和区别
- Android调用系统相机和图库
- 单选框和复选框
- 几秒前,几分钟前,几小时前,几天前,几月前,几年前的java实现
- 最少步数
- LINUX 使用tcgetattr函数与tcsetattr函数控制终端
- Cocos2dx android 上打包出现编译警告: 编码 UTF-8 的不可映射字符
- Struts2 拦截处理
- 第一篇文章
- iOS 设置启动图片
- coredata简单使用,插删改查
- Error querying database. Cause: java.lang.NumberFormatException: For input string: "否"
- 二叉树的创建