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

Commit8164bd6

Browse files
authored
Update Shortest Path in Binary Matrix.java
1 parent859072d commit8164bd6

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed
Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,37 @@
11
classSolution {
2+
privatefinalint[][]DIRS = {{1,0}, {0,1}, {-1,0}, {0, -1}, {1,1}, {-1,1}, {1, -1}, {-1, -1}};
3+
24
publicintshortestPathBinaryMatrix(int[][]grid) {
3-
intn =grid.length;
4-
if (n ==0 ||grid[0][0] ==1 ||grid[n -1][n -1] ==1) {
5+
if (grid[0][0] ==1) {
56
return -1;
67
}
8+
intnumRows =grid.length;
9+
intnumCols =grid[0].length;
10+
boolean[][]visited =newboolean[numRows][numCols];
711
Queue<int[]>queue =newLinkedList<>();
8-
intnumberOfSteps =0;
9-
boolean[][]visited =newboolean[n][n];
10-
queue.add(newint[] {0,0});
12+
queue.add(newint[]{0,0});
1113
visited[0][0] =true;
14+
intnumOfSteps =0;
1215
while (!queue.isEmpty()) {
16+
numOfSteps++;
1317
intsize =queue.size();
1418
while (size-- >0) {
1519
int[]removed =queue.remove();
16-
if (removed[0] ==n -1 &&removed[1] ==n -1) {
17-
returnnumberOfSteps +1;
20+
intx =removed[0];
21+
inty =removed[1];
22+
if (x ==numRows -1 &&y ==numCols -1) {
23+
returnnumOfSteps;
1824
}
19-
for (int[]dir :EIGHT_DIRS) {
20-
intnewX =removed[0] +dir[0];
21-
intnewY =removed[1] +dir[1];
22-
if (newX >=0
23-
&&newX <n
24-
&&newY >=0
25-
&&newY <n
26-
&& !visited[newX][newY]
27-
&&grid[newX][newY] ==0) {
28-
queue.add(newint[] {newX,newY});
25+
for (int[]dir :DIRS) {
26+
intnewX =x +dir[0];
27+
intnewY =y +dir[1];
28+
if (newX >=0 &&newY >=0 &&newX <numRows &&newY <numCols && !visited[newX][newY] &&grid[newX][newY] ==0) {
29+
queue.add(newint[]{newX,newY});
2930
visited[newX][newY] =true;
3031
}
3132
}
3233
}
33-
numberOfSteps++;
3434
}
3535
return -1;
3636
}
37-
38-
privatestaticfinalint[][]EIGHT_DIRS = {
39-
{0,1},{0,-1},{1,0},{-1,0},{1,-1},{-1,1},{-1,-1},{1,1}};
4037
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp