Time limit(ms): 1000
Memory limit(kb): 65535
Submission: 661
Accepted: 280
Accepted
搜索
Given a maze, find a shortest path from start to goal.
Description
Input consists serveral test cases.
First line of the input contains number of test case T.
For each test case the first line contains two integers N , M ( 1 <= N, M <= 100 ).
Each of the following N lines contain M characters. Each character means a cell of the map.
Here is the definition for chracter.
Constraint:
- For a character in the map:
- 'S' : start cell
- 'E' : goal cell
- '-' : empty cell
- '#' : obstacle cell
- no two start cell exists.
- no two goal cell exists.
Input
For each test case print one line containing shortest path. If there exists no path from start to goal, print -1.
Output
|
1
2
3
4
5
6
7
8
|
1
5 5
S-###
-----
##---
E#---
---##
|
Sample Input
|
1
2
|
9
|
/*
* 题意:求迷宫入口到出口的最短距离
* bfs大水题。。
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <cmath>
#include <queue>
using namespace std;
int dir[4][2] = { {-1,0}, {0,1}, {0,-1}, {1,0} };
char map[101][101];
bool vis[101][101];
int startI, startJ;
int endI, endJ;
int col, row;
struct Node {
int step;
int row;
int col;
};
void bfs() {
bool flag = true;
queue<Node>q;
Node p;
p.row = startI;
p.col = startJ;
p.step = 0;
for (int i = 0; i < 101; i++)
for (int j = 0; j < 101; j++)
vis[i][j] = 0;
fill(vis, vis + 101 * 101, 0);
q.push(p);
vis[p.row][p.col] = 1;
while (!q.empty()) {
Node p = q.front();
q.pop();
int r = p.row;
int c = p.col;
if (r == endI && c == endJ) {
flag = false;
cout << p.step << endl;
break;
}
for (int i = 0; i < 4; i++) {
Node s;
s.row = r + dir[i][0];
s.col = c + dir[i][1];
if (s.row>=0 && s.col>=0 && s.row<row && s.col<col && !vis[s.row][s.col] && map[s.row][s.col]!='#') {
vis[s.row][s.col] = 1;
s.step = p.step + 1;
q.push(s);
}
}
}
if (flag) {
cout << "-1" << endl;
}
}
int main(){
int t;
cin >> t;
while (t--) {
cin >> row >> col;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
cin >> map[i][j];
if (map[i][j] == 'S') {
startI = i;
startJ = j;
}
if (map[i][j] == 'E') {
endI = i;
endJ = j;
}
}
bfs();
}
return 0;
}

该博客讨论了如何在给定的迷宫中寻找从起点到终点的最短路径。输入包含多个测试用例,每个用例表示一个迷宫地图,其中'S'标记起点,'E'标记终点,'-'为空地,'#'为障碍。输出要求打印出每个测试用例的最短路径,若不存在路径则输出-1。
451

被折叠的 条评论
为什么被折叠?



