C++程序,用于查找使r行c列所有单元格变为黑色的最小操作次数
假设我们有两个数字r、c和一个大小为n x m的网格。一些单元格为黑色,其余为白色。在一个操作中,我们可以选择一些黑色单元格,并执行以下两个操作之一:
- 将该行中的所有单元格颜色更改为黑色,或者
- 将该列中的所有单元格颜色更改为黑色。
我们需要找到使第r行和第c列的单元格变为黑色的最小操作次数。如果不可能,则返回-1。
因此,如果输入如下所示:
| W | B | W | W | W |
| B | B | B | W | B |
| W | W | B | B | B |
r = 0 且 c = 3
则输出将为1,因为我们可以更改第一行以使其如下所示:
| B | B | B | B | B |
| B | B | B | W | B |
| W | W | B | B | B |
步骤
为了解决这个问题,我们将遵循以下步骤:
n := row count of grid m := column count of grid ans := inf for initialize i := 0, when i < n, update (increase i by 1), do: for initialize j := 0, when j < m, update (increase j by 1), do: if matrix[i, j] is same as 'B', then: ans := minimum of ans and (1 if i and r are different, otherwise 0) + (1 if j and c are different, otherwise 0) if ans > 2, then: return -1 Otherwise return ans
示例
让我们看看下面的实现以更好地理解:
#include <bits/stdc++.h>
using namespace std;
int solve(vector<vector<char>> matrix, int r, int c) {
int n = matrix.size();
int m = matrix[0].size();
int ans = 999999;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == 'B') {
ans = min(ans, (i != r) + (j != c));
}
}
}
if (ans > 2) {
return -1;
}
else
return ans;
}
int main() {
vector<vector<char>> matrix = { { 'W', 'B', 'W', 'W', 'W' }, { 'B', 'B', 'B', 'W', 'B' }, { 'W', 'W', 'B', 'B', 'B' } };
int r = 0, c = 3;
cout << solve(matrix, r, c) << endl;
}输入
{ { 'W', 'B', 'W', 'W', 'W' }, { 'B', 'B', 'B', 'W', 'B' }, { 'W', 'W', 'B', 'B', 'B' } }, 0, 3输出
1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP