0
点赞
收藏
分享

微信扫一扫

[BFS模板题] 数组版/STL版 以及记录路线

目录

​​题目 ​​


​​ 用数组模拟队列​​

​​运用queue​​

​​拓展:记录路线​​

题目 


 输入样例:

5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

输出样例:

8

 用数组模拟队列

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 110;

typedef pair<int, int> PII;
PII q[N*N];
int n,m;
int g[N][N],step[N][N];

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

int bfs()
{
memset(step, -1, sizeof step);

int x = 0, y = 0;
q[0] = {0, 0};
step[0][0] = 0;

while(x <= y)
{
auto t = q[x++];
for(int i = 0; i < 4; i ++)
{
int nx = t.first + dx[i], ny = t.second + dy[i];
if(nx>=0 && ny>=0 && nx<n && ny<m && !g[nx][ny] && step[nx][ny]==-1){
step[nx][ny] = step[t.first][t.second] + 1;
q[++y] = {nx, ny};
}
}
}
return step[n-1][m-1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
scanf("%d", &g[i][j]);
cout << bfs() << endl;
return 0;
}

运用queue

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 110;

typedef pair<int, int> PII;
queue<PII> q;
int n,m;
int g[N][N],step[N][N];

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

int bfs()
{
memset(step, -1, sizeof step);

int x = 0, y = 0;
q.push({0, 0});
step[0][0] = 0;

while(!q.empty())
{
auto t = q.front();
q.pop();

for(int i = 0; i < 4; i ++)
{
int nx = t.first + dx[i], ny = t.second + dy[i];
if(nx>=0 && ny>=0 && nx<n && ny<m && !g[nx][ny] && step[nx][ny]==-1){
step[nx][ny] = step[t.first][t.second] + 1;
q.push({nx, ny});
}
}
}
return step[n-1][m-1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
scanf("%d", &g[i][j]);
cout << bfs() << endl;
return 0;
}

拓展:记录路线

只需要新增加一个数对数组pre用来回忆即可

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 110;

typedef pair<int, int> PII;
PII q[N*N],pre[N][N];
int n,m;
int g[N][N],step[N][N];

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

int bfs()
{
memset(step, -1, sizeof step);

int x = 0, y = 0;
q[0] = {0, 0};
step[0][0] = 0;

while(x <= y)
{
auto t = q[x++];
for(int i = 0; i < 4; i ++)
{
int nx = t.first + dx[i], ny = t.second + dy[i];
if(nx>=0 && ny>=0 && nx<n && ny<m && !g[nx][ny] && step[nx][ny]==-1){
step[nx][ny] = step[t.first][t.second] + 1;
pre[nx][ny] = {t.first, t.second};
q[++y] = {nx, ny};
}
}
}

x = n-1, y = m-1;

while(x || y)
{
cout << x << ' ' << y << endl;
auto t = pre[x][y];
x = t.first, y = t.second;
}
return step[n-1][m-1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
scanf("%d", &g[i][j]);
cout << bfs() << endl;
return 0;
}

效果

[BFS模板题] 数组版/STL版 以及记录路线_bfs

[BFS模板题] 数组版/STL版 以及记录路线_#include_02 

 

 


举报

相关推荐

0 条评论