File tree Expand file tree Collapse file tree 2 files changed +83
-0
lines changed
main/java/leetcode/medium
test/java/leetcode/medium Expand file tree Collapse file tree 2 files changed +83
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode .medium ;
2+
3+ public class UpdateMatrix {
4+
5+ int [][] updateMatrix (int [][] mat ) {
6+ int rows = mat .length ;
7+ int cols = mat [0 ].length ;
8+ int [][] result = new int [rows ][cols ];
9+
10+ // Initialize the result matrix with maximum values
11+ for (int i = 0 ; i < rows ; i ++)
12+ for (int j = 0 ; j < cols ; j ++)
13+ result [i ][j ] = Integer .MAX_VALUE ;
14+
15+ // First pass: top-left to bottom-right
16+ for (int i = 0 ; i < rows ; i ++)
17+ for (int j = 0 ; j < cols ; j ++)
18+ if (mat [i ][j ] == 0 ) result [i ][j ] = 0 ;
19+ else {
20+ if (i > 0 )
21+ result [i ][j ] = Math .min (result [i ][j ], result [i - 1 ][j ] + 1 );
22+ if (j > 0 )
23+ result [i ][j ] = Math .min (result [i ][j ], result [i ][j - 1 ] + 1 );
24+ }
25+
26+ // Second pass: bottom-right to top-left
27+ for (int i = rows - 1 ; i >= 0 ; i --)
28+ for (int j = cols - 1 ; j >= 0 ; j --)
29+ if (mat [i ][j ] != 0 ) {
30+ if (i < rows - 1 )
31+ result [i ][j ] = Math .min (result [i ][j ], result [i + 1 ][j ] + 1 );
32+ if (j < cols - 1 )
33+ result [i ][j ] = Math .min (result [i ][j ], result [i ][j + 1 ] + 1 );
34+ }
35+
36+ return result ;
37+ }
38+
39+ }
Original file line number Diff line number Diff line change 1+ package leetcode .medium ;
2+
3+ import org .junit .jupiter .api .Test ;
4+
5+ import static org .junit .jupiter .api .Assertions .*;
6+
7+ class UpdateMatrixTest {
8+
9+ private final UpdateMatrix updateMatrix ;
10+
11+ UpdateMatrixTest () {
12+ updateMatrix = new UpdateMatrix ();
13+ }
14+
15+ @ Test
16+ void testUpdateMatrix1 () {
17+ int [][] mat = {
18+ {0 , 0 , 0 },
19+ {0 , 1 , 0 },
20+ {1 , 1 , 1 }
21+ };
22+ int [][] expected = {
23+ {0 , 0 , 0 },
24+ {0 , 1 , 0 },
25+ {1 , 2 , 1 }
26+ };
27+ assertArrayEquals (expected , updateMatrix .updateMatrix (mat ));
28+ }
29+
30+ @ Test
31+ void testUpdateMatrix2 () {
32+ int [][] mat = {
33+ {0 , 0 , 0 },
34+ {0 , 1 , 0 },
35+ {1 , 1 , 1 }
36+ };
37+ int [][] expected = {
38+ {0 , 0 , 0 },
39+ {0 , 1 , 0 },
40+ {1 , 2 , 1 }
41+ };
42+ assertArrayEquals (expected , updateMatrix .updateMatrix (mat ));
43+ }
44+ }
You can’t perform that action at this time.
0 commit comments