需要注意的是,每个点的权值是不一样的。普通的bfs,每个点的权值都相同,也就是每一层之间的距离是一样的,那么第一次搜索到这个点的时候,层次数最小,就是最短距离。但是这道题中层次数最小并不一定是距离最小,搜索了5层 ' X ',和搜索了6层 ' . ' 哪个距离短?很明显是6层的距离短。所以即便先前已经搜索到了这个点,后面的搜索依然需要将这个点的距离更新。所以我们不需要设vis数组来表示搜索过没有。只需要不断的更新直至队列为空就行了。此外,这道题还可以用A*的思路来解,换种说法也就是dijkstra算法。股价函数是h(n) = g(n) (搜索到当前点的代价)。
代码如下:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>
#define lson l, m, k << 1
#define rson m, r, k << 1| 1
using namespace std;
typedef long long int LL;
const int INF = 0x3f3f3f3f;
const int maxn = 205;
char G[maxn][maxn];
int d[maxn][maxn];
int n, m;
struct Node{
int x, y, d;
Node(int a, int b, int c){x = a; y = b; d = c;}
Node();
};
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
void bfs(){
int sx, sy, ex, ey;
for (int i = 0; i < n ;i++)
for (int j = 0; j < m; j++){
if (G[i][j] == 'S'){sx = i; sy = j;}
if (G[i][j] == 'T'){ex = i; ey = j;}
}
memset(d, INF, sizeof(d));
queue<Node> Q;
Q.push(Node(sx, sy, 0));
d[sx][sy] = 0;
while (!Q.empty()){
Node cur = Q.front();
Q.pop();
for (int i = 0; i < 4; i++){
int xx = cur.x + dx[i];
int yy = cur.y + dy[i];
if (xx >= 0 && xx < n && yy >= 0 && yy < m){
int cost;
if (G[xx][yy] == '#') continue;
if (G[xx][yy] == 'X') cost = 2;
if (G[xx][yy] == '.' || G[xx][yy] == 'T') cost = 1;
if (d[xx][yy] > d[cur.x][cur.y] + cost){
d[xx][yy] = d[cur.x][cur.y] + cost;
Q.push(Node(xx, yy, d[xx][yy]));
}
}
}
}
if (d[ex][ey] == INF) printf("impossible\n");
else printf("%d\n", d[ex][ey]);
}
int main()
{
//freopen("1.txt", "r", stdin);
while (~scanf("%d%d", &n, &m)){//因为没写这个,wa了无数遍
for (int i = 0; i < n; i++)
scanf("%s", G[i]);
bfs();
}
return 0;
}
本文深入探讨了图搜索算法中如何处理不同权值的问题,并通过具体示例解释了如何使用BFS算法解决特定路径寻找问题。文章还介绍了如何利用代价函数进行有效搜索,包括不使用标记数组来更新更优路径的方法。
7062

被折叠的 条评论
为什么被折叠?



