Skip to content

Commit ab5451b

Browse files
committed
solve unique paths
1 parent 86c96c3 commit ab5451b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

unique-paths/sora0319.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public int uniquePaths(int m, int n) {
3+
int[][] pathN = new int[m][n];
4+
boolean[][] visited = new boolean[m][n];
5+
pathN[0][0] = 1;
6+
7+
bfs(pathN, visited);
8+
return pathN[m-1][n-1];
9+
}
10+
public void bfs(int[][] pathN, boolean[][] visited){
11+
Queue<Pair> paths = new LinkedList<>();
12+
int[] mx = {0, 1};
13+
int[] my = {1, 0};
14+
15+
paths.offer(new Pair(0,0));
16+
17+
while(!paths.isEmpty()){
18+
Pair p = paths.poll();
19+
20+
for(int i = 0; i < 2; i++){
21+
int nx = mx[i] + p.x;
22+
int ny = my[i] + p.y;
23+
24+
if(nx >= pathN.length || ny >= pathN[0].length) continue;
25+
pathN[nx][ny] += pathN[p.x][p.y];
26+
if(!visited[nx][ny]){
27+
paths.offer(new Pair(nx, ny));
28+
visited[nx][ny] = true;
29+
}
30+
31+
}
32+
}
33+
}
34+
35+
class Pair{
36+
int x;
37+
int y;
38+
Pair(int x, int y){
39+
this.x = x;
40+
this.y = y;
41+
}
42+
}
43+
}
44+

0 commit comments

Comments
 (0)