-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset_matrix_zeroes.cpp
More file actions
91 lines (82 loc) · 2.08 KB
/
set_matrix_zeroes.cpp
File metadata and controls
91 lines (82 loc) · 2.08 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
// =====================================================================================
//
// Filename: set_matrix_zeroes.cpp
//
// Description: 73. Set Matrix Zeroes. Given a m x n matrix, if an element is 0, set
// its entire row and column to 0. Do it in-place.
//
// Version: 1.0
// Created: 10/18/2019 04:57:45 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <algorithm>
#include <vector>
using std::vector;
class Solution
{
public:
enum ZeroState
{
kZeroEmpty = 0,
kZeroHorizontal = 1,
kZeroVertical = 2,
};
void setZeroes(vector<vector<int>>& matrix)
{
if (matrix.size() == 0 || matrix[0].size() == 0)
{
return;
}
int rows = matrix.size();
int cols = matrix[0].size();
int n = std::max(rows, cols);
vector<int> states(n, kZeroEmpty);
// Keep zero cells in matrix
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (matrix[i][j] == 0)
{
states[i] |= kZeroHorizontal;
states[j] |= kZeroVertical;
}
}
}
// Set zero by zero states
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (states[i] & kZeroHorizontal || states[j] & kZeroVertical)
{
matrix[i][j] = 0;
}
}
}
}
};
int main(int argc, char* argv[])
{
vector<vector<int>> matrix = {
{0, 1, 2, 0},
{3, 4, 5, 2},
{1, 3, 1, 5},
};
Solution().setZeroes(matrix);
for (const auto& row: matrix)
{
for (const auto& val: row)
{
printf("%d ", val);
}
printf("\n");
}
return 0;
}