-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathSolution.java
More file actions
77 lines (73 loc) · 2.36 KB
/
Copy pathSolution.java
File metadata and controls
77 lines (73 loc) · 2.36 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
/**
* Time : O(N^2); Space: O(1)
* @tag : Array
* @by : Steven Cooks
* @date: Jun 6, 2015
*************************************************************************
* Description:
*
* Given a m x n matrix, if an element is 0, set its entire row and column
* to 0. Do it in place.
*
* Follow up:
* Could you devise a constant space solution?
*
*************************************************************************
* {@link https://leetcode.com/problems/set-matrix-zeroes/ }
* P.S. : use input space to achieve O(1) space
*/
package _073_SetMatrixZeroes;
/** see test {@link _073_SetMatrixZeroes.SolutionTest } */
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0) {
return;
}
int m = matrix.length;
int n = matrix[0].length;
int wasteRow = -1;
int wasteCol = -1;
// find '0' in matrix and label them in "waste" line and column
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
if (wasteRow == -1) {
// first time to find 0
wasteRow = i;
wasteCol = j;
} else {
// label in waste row and column
matrix[wasteRow][j] = 0;
matrix[i][wasteCol] = 0;
}
}
}
}
if (wasteRow == -1) {
return;
}
// set zeroes based on label
for (int col = 0; col < n; col++) {
if (matrix[wasteRow][col] == 0) {
// set zeroes on columns except waste columns
// we need that information for later use
if (col != wasteCol) {
for (int row = 0; row < m; row++) {
matrix[row][col] = 0;
}
}
}
}
for (int row = 0; row < m; row++) {
if (matrix[row][wasteCol] == 0) {
// set zeroes in the row
for (int col = 0; col < n; col++) {
matrix[row][col] = 0;
}
} else {
// clean this column
matrix[row][wasteCol] = 0;
}
}
}
}