最少步数(NYOJ 58)
2014-01-06 22:03
375 查看
最少步数
时间限制:3000 ms | 内存限制:65535 KB难度:4
描述
这有一个迷宫,有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)分别表示起点的行、列,终点的行、列。
输出输出最少走几步。
样例输入
2 3 1 5 7 3 1 6 7
样例输出
12 11
广搜。
第一次交的时候没有写标记数组,导致内存溢出了。
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <queue> using namespace std; struct node { int x; int y; int step; }; queue<node> q; node start, end; int s[4][2] = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}}; 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 visit[9][9]; int bfs () { int i, m, n; start.step = 0; visit[start.x][start.y] = 1; q.push(start); while (!q.empty()) { node e = q.front(); q.pop(); if(e.x == end.x && e.y == end.y) { return e.step; } for(i = 0; i < 4; i++) { m = e.x + s[i][0]; n = e.y + s[i][1]; if(map[m] == 0 && visit[m] == 0) { node e1; e1.x = m; e1.y = n; e1.step = e.step + 1; q.push(e1); visit[m] = 1; } } } return 0; } int main (void) { int n; scanf("%d", &n); while (n--) { scanf("%d %d %d %d", &start.x, &start.y, &end.x, &end.y); memset(visit, 0, sizeof(visit)); while (!q.empty()) { q.pop(); } int a = bfs(); printf("%d\n", a); } return 0; }
相关文章推荐
- NYOJ题目58-最少步数(搜索)
- nyoj--58 最少步数
- nyoj--58--最少步数(bfs&dfs)
- NYOJ 58 最少步数(dfs)
- DFS && BFS 最少步数(nyoj 58)
- NYOJ 58 最少步数(BFS)
- NYOJ 58 最少步数(BFS)
- nyoj--58--最少步数
- NYOJ 题目58 最少步数(BFS)
- NYOJ58 最少步数(搜索)
- NYOJ 58 最少步数(DFS)
- NYOJ-58:最少步数
- NYOJ-58 最少步数
- nyoj 58 最少步数(深搜dfs)
- 【DFS/BFS】NYOJ-58-最少步数(迷宫最短路径问题)
- nyoj-58 最少步数(DFS)
- NYOJ 题目58 最少步数(dfs)
- NYOJ_58 最少步数
- nyoj58 最少步数
- NYOJ 58 最少步数(深搜DFS)