广搜BFS 迷宫问题
//@auther Yang Zongjun
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
const int MAXN = 105;
const int INF = 2100000000;
char maze[MAXN][MAXN];
int d[MAXN][MAXN];
int n, m, sx, sy, gx, gy;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
typedef pair<int, int > P;
int bfs()
{
queue<P> que;
que.push(P(sx, sy));
d[sx][sy] = 0;
while(que.size())
{
P p = que.front();
que.pop();
if(p.first == gx && p.second == gy) break;
for(int i = 0; i < 4; i++)
{
int nx = p.first + dx[i], ny = p.second + dy[i];
if(0 <= nx && nx < n && 0 <= ny && ny < m && maze[nx][ny] != '#' && d[nx][ny] == INF)
{
que.push(P(nx, ny));
d[nx][ny] = d[p.first][p.second] + 1;
}
}
}
return d[gx][gy];
}
int main()
{
freopen("C:/Users/Administrator/Desktop/input.txt", "r", stdin);
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
scanf("%c", &maze[i][j]);
}
getchar();
}
for(int i =0; i < n; i++)
{
for(int j =0; j < m; j++)
{
if(maze[i][j] == 'S')
{
sx = i; sy = j;
}
if(maze[i][j] == 'G')
{
gx = i; gy = j;
}
}
}
for(int i = 0; i< n; i++)
for(int j = 0; j < m; j++)
d[i][j] = INF;
printf("%d\n", bfs());
return 0;
}
/*
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#
*/