用c++解决:给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。 两个相邻元素间的距离为 1 。
时间: 2024-09-08 21:00:35 浏览: 42
要解决这个问题,我们可以使用广度优先搜索(BFS)算法。首先,我们需要找到所有值为0的元素的位置,然后从这些位置开始进行BFS,逐层向外扩展,直到覆盖整个矩阵。在BFS的过程中,我们可以更新矩阵中每个元素到最近的0的距离。
下面是使用C++实现这一算法的步骤:
- 创建一个与输入矩阵同样大小的输出矩阵,初始时所有元素设置为一个很大的数(例如矩阵的行数与列数的乘积),用于表示距离。
- 找到所有值为0的元素,并将它们的位置加入到队列中,同时将它们在输出矩阵中的对应位置设置为0(表示最近距离)。
- 使用BFS遍历队列中的位置,对于队列中的每一个位置,检查其上下左右的邻居,如果邻居的值大于当前步数,则将其值更新为当前步数,并将该邻居的位置加入队列中。
- 重复步骤3,直到队列为空。
- 最后输出矩阵即为所求的结果。
下面是一个简化的C++代码示例:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int rows = mat.size();
int cols = mat[0].size();
vector<vector<int>> dist(rows, vector<int>(cols, INT_MAX));
queue<pair<int, int>> q;
// 初始化队列,找到所有0的位置
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (mat[i][j] == 0) {
dist[i][j] = 0;
q.push({i, j});
}
}
}
// 方向数组,分别表示上下左右四个方向的移动
vector<pair<int, int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// BFS
while (!q.empty()) {
auto [r, c] = q.front();
q.pop();
for (auto &dir : dirs) {
int nr = r + dir.first;
int nc = c + dir.second;
// 检查新位置是否有效且是否可以更新
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && dist[nr][nc] > dist[r][c] + 1) {
dist[nr][nc] = dist[r][c] + 1;
q.push({nr, nc});
}
}
}
return dist;
}
int main() {
vector<vector<int>> mat = {
{0, 0, 0},
{0, 1, 0},
{1, 1, 1}
};
vector<vector<int>> result = updateMatrix(mat);
for (const auto &row : result) {
for (int val : row) {
cout << val << " ";
}
cout << endl;
}
return 0;
}