File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public void setZeroes (int [][] matrix ) {
3+ int rows = matrix .length ;
4+ int cols = matrix [0 ].length ;
5+
6+ boolean firstRowHasZero = false ;
7+ boolean firstColHasZero = false ;
8+
9+ // 1. 첫 번째 행과 열에 0이 있는지 확인
10+ for (int i = 0 ; i < rows ; i ++) {
11+ if (matrix [i ][0 ] == 0 ) {
12+ firstColHasZero = true ;
13+ break ;
14+ }
15+ }
16+ for (int j = 0 ; j < cols ; j ++) {
17+ if (matrix [0 ][j ] == 0 ) {
18+ firstRowHasZero = true ;
19+ break ;
20+ }
21+ }
22+
23+ // 2. 나머지 행렬에서 0 찾기 (첫 번째 행과 열에 기록)
24+ for (int i = 1 ; i < rows ; i ++) {
25+ for (int j = 1 ; j < cols ; j ++) {
26+ if (matrix [i ][j ] == 0 ) {
27+ matrix [i ][0 ] = 0 ; // 해당 행 표시
28+ matrix [0 ][j ] = 0 ; // 해당 열 표시
29+ }
30+ }
31+ }
32+
33+ // 3. 첫 번째 행과 열의 정보를 기반으로 행렬 수정
34+ for (int i = 1 ; i < rows ; i ++) {
35+ for (int j = 1 ; j < cols ; j ++) {
36+ if (matrix [i ][0 ] == 0 || matrix [0 ][j ] == 0 ) {
37+ matrix [i ][j ] = 0 ;
38+ }
39+ }
40+ }
41+
42+ // 4. 첫 번째 열 복구
43+ if (firstColHasZero ) {
44+ for (int i = 0 ; i < rows ; i ++) {
45+ matrix [i ][0 ] = 0 ;
46+ }
47+ }
48+
49+ // 5. 첫 번째 행 복구
50+ if (firstRowHasZero ) {
51+ for (int j = 0 ; j < cols ; j ++) {
52+ matrix [0 ][j ] = 0 ;
53+ }
54+ }
55+ }
56+ }
57+
58+
You can’t perform that action at this time.
0 commit comments