2huk @ 2023-01-25 16:11:24
这是我的BFS代码
#include <iostream>
#include <queue>
using namespace std;
#define int long long
#define TRACE 1
#define tcout TRACE && cout
#define el printf("\n")
#define inf 0x7fffffff
int n, m;
int a[110][110];
int ans[10000010];
int cnt;
int x1, y1, x2, y2;
int maxn = -inf, minn = inf;
int res = -inf;
struct Node{
int x, y, s;
Node(){
}
Node(int _x, int _y, int _s){
x = _x;
y = _y;
s = _s;
}
};
int fx[] = {-1, 0, 0, 1};
int fy[] = {0, -1, 1, 0};
queue<Node> q;
void bfs(int x, int y){
q.push(Node(x, y, 0));
while(!q.empty()){
int x = q.front().x;
int y = q.front().y;
int s = q.front().s;
q.pop();
if(x == x2 && y == y2){
ans[++cnt] = s+1;
}
for(int i=0; i<4; i++){
int dx = x + fx[i];
int dy = y + fy[i];
if(dx >= 1 && dy >= 1 && dx <= n && dy <= m){
if(a[dx][dy] < a[x][y]){
q.push(Node(dx, dy, s+1));
}
}
}
}
}
signed main()
{
cin >> n >> m;
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
cin >> a[i][j];
if(a[i][j] > maxn){
maxn = a[i][j];
x1 = i, y1 = j;
}
if(a[i][j] < minn){
minn = a[i][j];
x2 = i, y2 = j;
}
}
}
bfs(x1, y1);
for(int i=1; i<=cnt; i++){
res = max(res, ans[i]);
}
cout << res;
el;
return 0;
}
这是我的提交记录
向大佬们求助!!
by 2huk @ 2023-01-25 16:13:40
蒟蒻初学BFS,麻烦dalao们帮助。
by a2lyaXNhbWUgbWFyaXNh @ 2023-01-25 16:33:35
据我所知,本题需要记忆化。
by sijiajun @ 2023-02-20 21:40:56
@2huk
正解应该是记忆化搜索吧?