Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit926f8dc

Browse files
committed
SetZeroes
1 parent3e0ebca commit926f8dc

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

‎array/SetZeroes.java

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
packageAlgorithms.array;
2+
3+
publicclassSetZeroes {
4+
publicstaticvoidmain(String[]strs) {
5+
int[][]matrix = {
6+
{0,0,0,5},{4,3,1,4},{0,1,1,4},{1,2,1,3},{0,0,1,1}
7+
};
8+
9+
setZeroes(matrix);
10+
}
11+
12+
publicstaticvoidsetZeroes(int[][]matrix) {
13+
if (matrix ==null ||matrix.length ==0
14+
||matrix[0].length ==0) {
15+
return;
16+
}
17+
18+
booleanrow1Zero =false;
19+
booleancol1Zero =false;
20+
21+
introws =matrix.length;
22+
intcols =matrix[0].length;
23+
24+
// Determine if the first column should be Zero.
25+
for (inti =0;i <rows;i++) {
26+
if (matrix[i][0] ==0) {
27+
col1Zero =true;
28+
break;
29+
}
30+
}
31+
32+
// Determine if the first row should be Zero.
33+
for (inti =0;i <cols;i++) {
34+
if (matrix[0][i] ==0) {
35+
row1Zero =true;
36+
break;
37+
}
38+
}
39+
40+
// we use the first row and the first col as the flag to record the
41+
// cells whether or not set to 0.
42+
for (inti =1;i <rows;i++) {
43+
for (intj =1;j <cols;j++) {
44+
// 注意了,这个矩阵是0和非0,并不是0和1.
45+
if (matrix[i][j] ==0) {
46+
// set the flag in the first line and the first column
47+
matrix[i][0] =0;
48+
matrix[0][j] =0;
49+
}
50+
}
51+
}
52+
53+
// set the inner cells.
54+
// Be careful: i, j start from 1.
55+
for (inti =1;i <rows;i++) {
56+
for (intj =1;j <cols;j++) {
57+
if (matrix[i][0] ==0
58+
||matrix[0][j] ==0) {
59+
matrix[i][j] =0;
60+
}
61+
}
62+
}
63+
64+
// set the first row.
65+
if (row1Zero) {
66+
for (inti =0;i <cols;i++) {
67+
matrix[0][i] =0;
68+
}
69+
}
70+
71+
// set the first col.
72+
if (col1Zero) {
73+
for (inti =0;i <rows;i++) {
74+
matrix[i][0] =0;
75+
}
76+
}
77+
78+
return;
79+
}
80+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp