icpc:problems:矩阵距离
problems | |
---|---|
名称 | 矩阵距离 |
题目编号 | None |
题目链接 | zl.zhili-edu.com/… |
来源 | Zhili |
算法分类 | 搜索, BFS, 多源广搜, BFS_例题 |
难易程度 | 容易 |
矩阵距离
想法
将多个1作为起点,BFS扩展这些起点,每个点第一次访问时必定为最小距离。
代码实现
#include<cstdio> #include<queue> using namespace std; const int N = 1010; char maps[N][N]; int dis[N][N]; bool vis[N][N]; int x_turn[4]={1, -1, 0, 0}; int y_turn[4]={0, 0, 1, -1}; int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= n; ++i) { scanf("\n%s", maps[i]+1); } queue<pair<int, int> >qu; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if(maps[i][j] == '1') { qu.push(make_pair(i, j)); vis[i][j] = true; } while(!qu.empty()) { pair<int, int>now = qu.front(); qu.pop(); for (int i = 0; i < 4; ++i) { int xx = now.first + x_turn[i], yy = now.second + y_turn[i]; if(vis[xx][yy] || xx < 1 || xx > n || yy < 1 || yy > m)continue; vis[xx][yy] = true; dis[xx][yy] = dis[now.first][now.second] + 1; qu.push(make_pair(xx, yy)); } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { printf("%d ", dis[i][j]); } printf("\n"); } return 0; }
/app/www/public/data/pages/icpc/problems/矩阵距离.txt · 最后更改: 2023/07/02 10:53 由 温婕莺