fork download
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. void markRow(vector<vector<int>> &matrix, int n, int m, int i) {
  6. // set all non-zero elements as -1 in the row i:
  7. for (int j = 0; j < m; j++) {
  8. if (matrix[i][j] != 0) {
  9. matrix[i][j] = -1;
  10. }
  11. }
  12. }
  13.  
  14.  
  15. void markCol(vector<vector<int>> &matrix, int n, int m, int j) {
  16. // set all non-zero elements as -1 in the col j:
  17. for (int i = 0; i < n; i++) {
  18. if (matrix[i][j] != 0) {
  19. matrix[i][j] = -1;
  20. }
  21. }
  22. }
  23.  
  24. vector<vector<int>> zeroMatrix(vector<vector<int>> &matrix, int n, int m) {
  25.  
  26. // Set -1 for rows and cols
  27. // that contains 0. Don't mark any 0 as -1:
  28.  
  29. for (int i = 0; i < n; i++) {
  30. for (int j = 0; j < m; j++) {
  31. if (matrix[i][j] == 0) {
  32. markRow(matrix, n, m, i);
  33. markCol(matrix, n, m, j);
  34. }
  35. }
  36. }
  37.  
  38. // Finally, mark all -1 as 0:
  39. for (int i = 0; i < n; i++) {
  40. for (int j = 0; j < m; j++) {
  41. if (matrix[i][j] == -1) {
  42. matrix[i][j] = 0;
  43. }
  44. }
  45. }
  46.  
  47. return matrix;
  48. }
  49.  
  50. int main()
  51. {
  52. vector<vector<int>> matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
  53. int n = matrix.size();
  54. int m = matrix[0].size();
  55. vector<vector<int>> ans = zeroMatrix(matrix, n, m);
  56.  
  57. cout << "The Final matrix is: n";
  58. for (auto it : ans) {
  59. for (auto ele : it) {
  60. cout << ele << " ";
  61. }
  62. cout << "n";
  63. }
  64. return 0;
  65. }
  66.  
  67.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
The Final matrix is: n1 0 1 n0 0 0 n1 0 1 n