forked from ravikartar/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setmatrixzero
65 lines (58 loc) · 1.34 KB
/
setmatrixzero
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;
void setZeroes(vector < vector < int >> & matrix) {
int rows = matrix.size(), cols = matrix[0].size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
int ind = i - 1;
while (ind >= 0) {
if (matrix[ind][j] != 0) {
matrix[ind][j] = -1;
}
ind--;
}
ind = i + 1;
while (ind < rows) {
if (matrix[ind][j] != 0) {
matrix[ind][j] = -1;
}
ind++;
}
ind = j - 1;
while (ind >= 0) {
if (matrix[i][ind] != 0) {
matrix[i][ind] = -1;
}
ind--;
}
ind = j + 1;
while (ind < cols) {
if (matrix[i][ind] != 0) {
matrix[i][ind] = -1;
}
ind++;
}
}
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] <= 0) {
matrix[i][j] = 0;
}
}
}
}
int main() {
vector < vector < int >> arr;
arr = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
setZeroes(arr);
cout << "The Final Matrix is " << endl;
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[0].size(); j++) {
cout << arr[i][j] << " ";
}
cout << "\n";
}
}