-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset matrix zero.cpp
More file actions
116 lines (95 loc) · 2.64 KB
/
Copy pathset matrix zero.cpp
File metadata and controls
116 lines (95 loc) · 2.64 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Problem Statement Link - https://leetcode.com/problems/set-matrix-zeroes/
// Space - O(m*n)
class Solution {
public:
void nullifyRow(vector<vector<int>>& matrix, int row) {
for (int j = 0; j < matrix[0].size(); j++)
{
matrix[row][j] = 0;
}
}
void nullifycolumn(vector<vector<int>>& matrix, int col) {
for (int i= 0; i < matrix.size(); i++)
{
matrix[i][col] = 0;
}
}
void setZeroes(vector<vector<int>>& matrix) {
vector<bool> row;
vector<bool> column;
// bool* row = new bool[matrix.size()];
// bool* column = new bool[matrix[0].size()];
for (int i= 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[0].size();j++) {
if (matrix[i][j] == 0) {
row[i] = true;
column[j] = true;
}
}
}
for (int i= 0; i < row.size(); i++) {
if (row[i])
{
nullifyRow(matrix, i);
}
}
for (int j= 0; j < column.size(); j++) {
if (column[j])
{
nullifycolumn(matrix, j);
}
}
}
};
// Space - O(m +n)
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<bool> row(n, false);
vector<bool> col(m, false);
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(!matrix[i][j]){
row[i] = true;
col[j] = true;
}
}
}
for(int i = 0; i<n; i++){
for(int j = 0; j<m; j++){
if(row[i] || col[j])
matrix[i][j] = 0;
}
}
}
};
// Space - O(1)
class Solution
{
public:
void setZeroes( vector<vector<int>>& arr )
{
int col0 = 1, row = arr.size(), col = arr[ 0 ].size() ;
for( int i = 0 ; i < row ; i ++ )
{
if( arr[ i ][ 0 ] == 0 ) col0 = 0 ;
for( int j = 1 ; j < col ; j ++ )
{
if( arr[ i ][ j ] == 0 ) arr[ i ][ 0 ] = arr[ 0 ][ j ] = 0 ;
}
}
for( int i = row - 1 ; i >= 0 ; i -- )
{
for( int j = col - 1 ; j >= 1 ; j -- )
{
if( arr[ i ][ 0 ] == 0 || arr[ 0 ][ j ] == 0 )
{
arr[ i ][ j ] = 0 ;
}
}
if( col0 == 0 ) arr[ i ][ 0 ] = 0 ;
}
}
};