#include <bits/stdc++.h>
using namespace std;
#define maxn 110
int n, m;
char board[maxn][maxn];
bool visited[maxn][maxn];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
bool ok = false;
int len = 0;
struct Point {
int x;
int y;
Point(int _x, int _y) {
x = _x;
y = _y;
}
};
/*
@startx:x坐标
@starty:y坐标
*/
void findPath(int startx,int starty) {
Point start(startx, starty);
visited[startx][starty] = true;
queue<Point> qu;
qu.push(start);
//bfs找最短路
while(!qu.empty()) {
int size = qu.size();//注意点:一定要先把本层的长度记录下来
for(int i = 0; i < size; i++) {//分层搜索
Point p = qu.front();
qu.pop();
int x = p.x;
int y = p.y;
if(board[x][y] == 'T') { //找到了,跳出for循环
ok = true;
return;
}
for(int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < n && ny >= 0 && ny < m && board[nx][ny] != '#' && !visited[nx][ny]) {
visited[nx][ny] = true;
Point newPoint(nx, ny);
qu.push(newPoint);
}
}
}
len++;
}
}
int main() {
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
std::ios::sync_with_stdio(false);
cin >> n >> m;
int startx = -1;
int starty = -1;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
cin >> board[i][j];
visited[i][j] = false;
if(board[i][j] == 'S') {//记录起点
startx = i;
starty = j;
}
}
}
findPath(startx, starty);
if(ok) {
cout << len << endl;
} else {
cout << -1 << endl;
}
return 0;
}
计蒜客 走迷宫2(bfs搜索)
最新推荐文章于 2022-01-13 12:53:19 发布