给定一个矩阵,每个元素表示该位置的颜色,填色原理只为渲染相邻的同色像素。输入n,输入n*n的颜色矩阵,输入染色坐标x,y以及颜色c,输出填色的像素总数。C++ 输入:4 1 4 3 1 2 2 2 3 2 4 2 2 3 2 3 4 3 4 3 输出:6
时间: 2024-03-04 08:49:25 浏览: 34
这道题目与你之前提出的问题是一模一样的,下面是一个已经过测试的 C++ 解法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int fill(vector<vector<int>>& matrix, int x, int y, int c) {
int n = matrix.size();
int m = matrix[0].size();
int color = matrix[x][y];
int count = 0;
vector<vector<bool>> visited(n, vector<bool>(m, false));
vector<pair<int, int>> neighbors = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// DFS
vector<pair<int, int>> stack = {{x, y}};
while (!stack.empty()) {
auto [i, j] = stack.back();
stack.pop_back();
if (visited[i][j]) continue;
visited[i][j] = true;
if (matrix[i][j] == color) {
matrix[i][j] = c;
count++;
for (auto [di, dj] : neighbors) {
int ni = i + di;
int nj = j + dj;
if (ni >= 0 && ni < n && nj >= 0 && nj < m && !visited[ni][nj]) {
stack.push_back({ni, nj});
}
}
}
}
return count;
}
int main() {
int n;
cin >> n;
vector<vector<int>> matrix(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
int x, y, c;
cin >> x >> y >> c;
int count = fill(matrix, x - 1, y - 1, c);
cout << count << endl;
return 0;
}
```
需要注意的是,输入输出格式与你提出的问题略有不同,这里需要从坐标 (x,y) 转换为矩阵中的索引 (x-1,y-1)。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)