Skip to content

Commit db59270

Browse files
committed
solve 73.set-matrix-zeroes
1 parent 5fc3181 commit db59270

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

vscode/73.set-matrix-zeroes.java

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
* @lc app=leetcode id=73 lang=java
3+
*
4+
* [73] Set Matrix Zeroes
5+
*
6+
* https://leetcode.com/problems/set-matrix-zeroes/description/
7+
*
8+
* algorithms
9+
* Medium (40.62%)
10+
* Likes: 1243
11+
* Dislikes: 219
12+
* Total Accepted: 231.3K
13+
* Total Submissions: 568.7K
14+
* Testcase Example: '[[1,1,1],[1,0,1],[1,1,1]]'
15+
*
16+
* Given a m x n matrix, if an element is 0, set its entire row and column to
17+
* 0. Do it in-place.
18+
*
19+
* Example 1:
20+
*
21+
*
22+
* Input:
23+
* [
24+
* [1,1,1],
25+
* [1,0,1],
26+
* [1,1,1]
27+
* ]
28+
* Output:
29+
* [
30+
* [1,0,1],
31+
* [0,0,0],
32+
* [1,0,1]
33+
* ]
34+
*
35+
*
36+
* Example 2:
37+
*
38+
*
39+
* Input:
40+
* [
41+
* [0,1,2,0],
42+
* [3,4,5,2],
43+
* [1,3,1,5]
44+
* ]
45+
* Output:
46+
* [
47+
* [0,0,0,0],
48+
* [0,4,5,0],
49+
* [0,3,1,0]
50+
* ]
51+
*
52+
*
53+
* Follow up:
54+
*
55+
*
56+
* A straight forward solution using O(mn) space is probably a bad idea.
57+
* A simple improvement uses O(m + n) space, but still not the best
58+
* solution.
59+
* Could you devise a constant space solution?
60+
*
61+
*
62+
*/
63+
class Solution {
64+
public void setZeroes(int[][] matrix) {
65+
boolean isFirstCol = false;
66+
int row = matrix.length;
67+
int col = matrix[0].length;
68+
69+
for (int i = 0; i < row; i++) {
70+
if (matrix[i][0] == 0) {
71+
isFirstCol = true;
72+
}
73+
74+
for (int j = 1; j < col; j++) {
75+
if (matrix[i][j] == 0) {
76+
matrix[i][0] = 0;
77+
matrix[0][j] = 0;
78+
}
79+
}
80+
}
81+
82+
for (int i = 1; i < row; i++) {
83+
for (int j = 1; j < col; j++) {
84+
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
85+
matrix[i][j] = 0;
86+
}
87+
}
88+
}
89+
90+
if (matrix[0][0] == 0) {
91+
for (int j = 0; j < col; j++) {
92+
matrix[0][j] = 0;
93+
}
94+
}
95+
96+
if (isFirstCol) {
97+
for (int i = 0; i < row; i++) {
98+
matrix[i][0] = 0;
99+
}
100+
}
101+
}
102+
}
103+

0 commit comments

Comments
 (0)