题目描述
小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。
小明只能向上下左右四个方向移动。
输入
输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。
每组输入的第一行是两个整数N和M(1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:
‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过
输入数据保证有且仅有一个起点和终点。
每组输入的第一行是两个整数N和M(1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:
‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过
输入数据保证有且仅有一个起点和终点。
输出
对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1。
样例输入
1
5 5
S-###
-----
##---
E#---
---##
样例输出
9
1 #define Question5 2 #ifdef Question5 3 4 #define UnDebug 5 6 #ifdef Debug 7 #include <ctime> 8 #endif 9 10 #include <iostream> 11 #include <cstring> 12 #include <queue> 13 #include <cstdio> 14 15 using namespace std; 16 17 typedef pair<int, int> P; 18 const int Max = 100; 19 const int INF = -1; 20 char Map[Max + 10][Max + 10]; 21 int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; 22 int diction[Max + 10][Max + 10]; 23 int sx, sy, ex, ey; 24 25 void InputMap(int N, int M); 26 void OutputMap(int N, int M); 27 void BFS(int N, int M); 28 29 int main() 30 { 31 #ifdef Debug 32 freopen("in.txt", "r", stdin); 33 clock_t start, finish; 34 double totaltime; 35 start = clock(); 36 #endif 37 38 int T, N, M; 39 cin >> T; 40 while (T--) 41 { 42 cin >> N >> M; 43 InputMap(N, M); 44 BFS(N, M); 45 cout << diction[ey][ex] << endl; 46 } 47 48 #ifdef Debug 49 finish = clock(); 50 totaltime = (double)(finish - start) / CLOCKS_PER_SEC; 51 cout << "Times : " << totaltime * 1000 << "ms" << endl; 52 system("pause"); 53 #endif 54 return 0; 55 } 56 57 void InputMap(int N, int M) 58 { 59 bool sok = 1, eok = 1; 60 for (int i = 0; i < N; i++) 61 { 62 cin >> Map[i]; 63 for (int j = 0; j < M; j++) 64 { 65 if (sok && Map[i][j] == 'S') 66 { 67 sx = j; 68 sy = i; 69 sok = 0; 70 } 71 if (eok && Map[i][j] == 'E') 72 { 73 ex = j; 74 ey = i; 75 eok = 0; 76 } 77 } 78 } 79 } 80 void OutputMap(int N, int M) 81 { 82 for (int i = 0; i < N; i++) 83 { 84 for (int j = 0; j < M; j++) 85 { 86 cout << Map[i][j] << " "; 87 } 88 cout << endl; 89 } 90 } 91 92 void BFS(int N, int M) 93 { 94 queue<P> que; 95 memset(diction, INF, sizeof(diction)); 96 que.push(P(sy, sx)); 97 diction[sy][sx] = 0; 98 99 while (!que.empty()) 100 { 101 P curPoint = que.front(); 102 que.pop(); 103 for (int i = 0; i < 4; i++) 104 { 105 int newx = curPoint.second + dx[i]; 106 int newy = curPoint.first + dy[i]; 107 108 if (newy >= 0 && newy < N && 109 newx >= 0 && newx < M && 110 Map[newy][newx] != '#' && 111 diction[newy][newx] == INF) 112 { 113 que.push(P(newy, newx)); 114 diction[newy][newx] = diction[curPoint.first][curPoint.second] + 1; 115 if (newx == ex && newy == ey) 116 return; 117 } 118 } 119 } 120 } 121 122 #endif
浙公网安备 33010602011771号