uva11624

本文详细展示了BFS(广度优先搜索)算法在解决最短路径问题上的应用。通过实例代码解释了如何初始化并更新网格中的距离,以及如何找到起点到终点的最短步数。代码中涉及到了队列、矩阵和图的遍历等概念,对于理解BFS算法及其在路径查找问题中的应用具有指导意义。
摘要由CSDN通过智能技术生成
#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值