fork download
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. vector<vector<int>> zeroMatrix(vector<vector<int>> &matrix, int n, int m) {
  6.  
  7. // int row[n] = {0}; --> matrix[..][0]
  8. // int col[m] = {0}; --> matrix[0][..]
  9.  
  10. int col0 = 1;
  11. // step 1: Traverse the matrix and
  12. // mark 1st row & col accordingly:
  13. for (int i = 0; i < n; i++) {
  14. for (int j = 0; j < m; j++) {
  15. if (matrix[i][j] == 0) {
  16. // mark i-th row:
  17. matrix[i][0] = 0;
  18.  
  19. // mark j-th column:
  20. if (j != 0)
  21. matrix[0][j] = 0;
  22. else
  23. col0 = 0;
  24. }
  25. }
  26. }
  27.  
  28. // Step 2: Mark with 0 from (1,1) to (n-1, m-1):
  29. for (int i = 1; i < n; i++) {
  30. for (int j = 1; j < m; j++) {
  31. if (matrix[i][j] != 0) {
  32. // check for col & row:
  33. if (matrix[i][0] == 0 || matrix[0][j] == 0) {
  34. matrix[i][j] = 0;
  35. }
  36. }
  37. }
  38. }
  39.  
  40. //step 3: Finally mark the 1st col & then 1st row:
  41. if (matrix[0][0] == 0) {
  42. for (int j = 0; j < m; j++) {
  43. matrix[0][j] = 0;
  44. }
  45. }
  46. if (col0 == 0) {
  47. for (int i = 0; i < n; i++) {
  48. matrix[i][0] = 0;
  49. }
  50. }
  51.  
  52. return matrix;
  53. }
  54.  
  55. int main()
  56. {
  57. vector<vector<int>> matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
  58. int n = matrix.size();
  59. int m = matrix[0].size();
  60. vector<vector<int>> ans = zeroMatrix(matrix, n, m);
  61.  
  62. cout << "The Final matrix is: n";
  63. for (auto it : ans) {
  64. for (auto ele : it) {
  65. cout << ele << " ";
  66. }
  67. cout << "n";
  68. }
  69. return 0;
  70. }
  71.  
  72.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
The Final matrix is: n1 0 1 n0 0 0 n1 0 1 n