C++ 中的布尔矩阵问题?
此处我们将看到一个有趣的布尔矩阵问题。给定一个布尔矩阵,其中包含 0 和 1。我们的目标是找到 1 被标记的位置。如果 1 被标记在位置 mat[i,j],那么我们将第 i 行和第 j 列的所有条目都设为 1。让我们举个例子。如果矩阵如下所示:-
1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0
那么经过修改后,结果将是 -
1 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1
算法
matrixUpdate(matrix[R,C])
begin define 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 Matrix 1001 0000 0000 0100 Updated Matrix 1111 1101 1101 1111
广告