C ++中的布尔矩阵问题?
在这里,我们将看到一个有趣的布尔矩阵问题。给出了一个布尔矩阵,其中包含0和1。我们的目标是找到标记为1的位置。如果将1标记在mat [i,j]位置,则将所有条目添加到第i行和第j列的1。让我们来看一个例子。如果矩阵如下所示-
1 0 0 10 0 0 0
0 0 0 0
0 1 0 0
然后修改后,它将是-
1 1 1 11 1 0 1
1 1 0 1
1 1 1 1
算法
matrixUpdate(matrix [R,C])
begindefine two matrices row[R] and col[C], and fill them with 0
mark the row and column indices of mat[R,C] where 1 is placed into the row[R] and col[C] matrices
check row[R] and col[C] if the place is marked, then fill all places of that row and column with 1’s.
end
示例
#include <iostream>#define R 4
#define C 4
using namespace std;
void updateMatrix(bool mat[R][C]) {
bool row[R];
bool col[C];
int i, j;
for (int i = 0; i < R; i++) { //set all elements of row matrix as 0
row[i] = 0;}
for (i = 0; i < C; i++) { //set all elements of col matrix as 0
col[i] = 0;}
for (int i = 0; i < R; i++) { //mark row and col matrix to identify where 1 is present
for (int j = 0; j < C; j++) {
if (mat[i][j] == 1) {
row[i] = 1;
col[j] = 1;
}
}
}
for (i = 0; i < R; i++) { //set all 1s to the row and col, where 1 is marked
for (j = 0; j < C; j++) {
if ( row[i] == 1 || col[j] == 1 ) {
mat[i][j] = 1;
}
}
}
}
void displayMatrix(bool mat[R][C]) {
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cout << mat[i][j];
}
cout << endl;
}
}
main() {
bool mat[R][C] = { {1, 0, 0, 1},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 1, 0, 0}
};
cout << "Given Matrix" << endl;
displayMatrix(mat);
updateMatrix(mat);
cout << "Updated Matrix" << endl;
displayMatrix(mat);
}
输出结果
Given Matrix1001
0000
0000
0100
Updated Matrix
1111
1101
1101
1111
以上是 C ++中的布尔矩阵问题? 的全部内容, 来源链接: utcz.com/z/326603.html