赞
踩
本专题用来计算使用多源BFS和双端队列BFS求解的题目。
题目1:173矩阵距离
C++代码如下,
#include <iostream> #include <queue> #include <cstring> using namespace std; const int N = 1010; int g[N][N]; int d[N][N]; int n, m; int main() { queue<pair<int,int>> q; memset(d, -1, sizeof d); cin >> n >> m; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { char c; cin >> c; g[i][j] = c - '0'; if (g[i][j]) { q.push(make_pair(i,j)); d[i][j] = 0; } } } int dirs[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}}; while (!q.empty()) { auto t = q.front(); q.pop(); //t下一步可以走到哪里 for (int k = 0; k < 4; ++k) { int x = t.first + dirs[k][0]; int y = t.second + dirs[k][1]; if (x < 1 || x > n || y < 1 || y > m) continue; if (d[x][y] != -1) continue; q.push(make_pair(x,y)); d[x][y] = d[t.first][t.second] + 1; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cout << d[i][j] << " "; } cout << endl; } return 0; }
题目2:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。