多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 布尔矩阵问题 > 原文: [https://www.geeksforgeeks.org/a-boolean-matrix-question/](https://www.geeksforgeeks.org/a-boolean-matrix-question/) 给定大小为 MXN 的布尔矩阵 mat [M] [N],请对其进行修改,以使如果矩阵单元 mat [i] [j]为 1(或 true),则使第 i 行和第 j 列的所有单元格均为 1。 ``` Example 1 The matrix 1 0 0 0 should be changed to following 1 1 1 0 Example 2 The matrix 0 0 0 0 0 1 should be changed to following 0 0 1 1 1 1 Example 3 The matrix 1 0 0 1 0 0 1 0 0 0 0 0 should be changed to following 1 1 1 1 1 1 1 1 1 0 1 1 ``` **方法 1(使用两个临时数组)** 1)创建两个临时数组 row [M]和 col [N]。 将 row []和 col []的所有值初始化为 0。 2)遍历输入矩阵 mat [M] [N]。 如果看到输入 mat [i] [j]为 true,则将 row [i]和 col [j]标记为 true。 3)再次遍历输入矩阵 mat [M] [N]。 对于每个入口 mat [i] [j],检查 row [i]和 col [j]的值。 如果两个值(row [i]或 col [j])中的任何一个为 true,则将 mat [i] [j]标记为 true。 感谢 Dixit Sethi 提出了这种方法。 ## C++ ```cpp // C++ Code For A Boolean Matrix Question #include <bits/stdc++.h> using namespace std; #define R 3 #define C 4 void modifyMatrix(bool mat[R][C]) {     bool row[R];     bool col[C];     int i, j;     /* Initialize all values of row[] as 0 */     for (i = 0; i < R; i++)     {     row[i] = 0;     }     /* Initialize all values of col[] as 0 */     for (i = 0; i < C; i++)     {     col[i] = 0;     }     // Store the rows and columns to be marked as     // 1 in row[] and col[] arrays respectively     for (i = 0; i < R; i++)     {         for (j = 0; j < C; j++)         {             if (mat[i][j] == 1)             {                 row[i] = 1;                 col[j] = 1;             }         }     }     // Modify the input matrix mat[] using the      // above constructed row[] and col[] arrays     for (i = 0; i < R; i++)     {         for (j = 0; j < C; j++)         {             if ( row[i] == 1 || col[j] == 1 )             {                 mat[i][j] = 1;             }         }     } } /* A utility function to print a 2D matrix */ void printMatrix(bool mat[R][C]) {     int i, j;     for (i = 0; i < R; i++)     {         for (j = 0; j < C; j++)         {             cout << mat[i][j];         }         cout << endl;     } } // Driver Code int main() {     bool mat[R][C] = { {1, 0, 0, 1},                        {0, 0, 1, 0},                        {0, 0, 0, 0}};     cout << "Input Matrix \n";     printMatrix(mat);     modifyMatrix(mat);     printf("Matrix after modification \n");     printMatrix(mat);     return 0; } // This code is contributed  // by Akanksha Rai(Abby_akku) ```