#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int INF = 0x3f3f3f3f,maxn = 1007, DIR[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int r, c,m[maxn][maxn],vis[maxn][maxn];
char ch[maxn][maxn];
queue<pair<int,int>> q;
void Init() {
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
int x = q.front().first,y = q.front().second;
q.pop();
for (int j = 0; j < 4; j++) {
int nx = x + DIR[j][0];
int ny = y + DIR[j][1];
if (nx >= 0 && nx < r && ny >= 0 && ny < c && ch[nx][ny] == '.' && m[nx][ny] == INF) {
m[nx][ny] = m[x][y] + 1;
q.push(make_pair(nx, ny));
}
}
}
}
}
int bfs(int _x, int _y) {
int ans = 0;
q.push({ _x,_y });
vis[_x][_y] = 1;
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
int x = q.front().first, y = q.front().second;
q.pop();
if (x == 0 || y == 0 || x == r - 1 || y == c - 1) return ans + 1;
for (int j = 0; j < 4; j++) {
int nx = x + DIR[j][0];
int ny = y + DIR[j][1];
if (nx >= 0 && nx < r && ny >= 0 && ny < c && !vis[nx][ny] && ch[nx][ny] == '.' && ans + 1 < m[nx][ny]) {
vis[nx][ny] = 1;
q.push(make_pair(nx, ny));
}
}
}
++ans;
}
return INF;
}
int main()
{
int t;
cin >> t;
while (t--) {
cin >> r >> c;
int x, y;
while (!q.empty())q.pop();
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
vis[i][j] = 0;
cin >> ch[i][j];
m[i][j] = INF;
if (ch[i][j] == 'F') {
m[i][j] = 0;
q.push(make_pair(i, j));
}
else if (ch[i][j] == 'J') {
x = i;
y = j;
}
}
}
Init();
int ans = bfs(x, y);
if (ans == INF) cout << "IMPOSSIBLE" << endl;
else cout << ans << endl;
}
return 0;
}
uva11624
最新推荐文章于 2024-09-02 20:21:30 发布
本文详细展示了BFS(广度优先搜索)算法在解决最短路径问题上的应用。通过实例代码解释了如何初始化并更新网格中的距离,以及如何找到起点到终点的最短步数。代码中涉及到了队列、矩阵和图的遍历等概念,对于理解BFS算法及其在路径查找问题中的应用具有指导意义。
摘要由CSDN通过智能技术生成