1+ /*
2+
3+ 1. 아이디어 : 1~maxMove까지 움직였을때, 경계를 벗어나는 모든 경우의 수 구하기
4+ 1차 시도: 메모제이션 없이 bfs로만 구현, 시간복잡도 O(4^maxMove)로 메모리 초과
5+ 2차 시도: 메모제이션 적용, weight와 visited 배열을 추가하여 상태체크및 중복 방문 방지
6+
7+ 2. 시간복잡도 : O(m*n*maxMove)
8+
9+ 3. 자료구조/알고리즘 : BFS, 메모제이션
10+
11+ */
12+
13+ class Solution {
14+
15+ private static int MOD = 1000000007 ;
16+ private int [] dy = {0 ,1 ,-1 ,0 };
17+ private int [] dx = {1 ,0 ,0 ,-1 };
18+
19+ public int findPaths (int m , int n , int maxMove , int startRow , int startColumn ) {
20+ // 값이 너무 클 경우 10^9 + 7로 모듈러 연산
21+
22+ Deque <int []> dq = new ArrayDeque <>();
23+ dq .add (new int []{startRow , startColumn , 0 });
24+
25+ long [][][] weight = new long [m ][n ][maxMove +1 ];
26+ boolean [][][] visited = new boolean [m ][n ][maxMove +1 ];
27+ long ans = 0L ;
28+
29+ weight [startRow ][startColumn ][0 ] = 1 ;
30+ visited [startRow ][startColumn ][0 ] = true ;
31+
32+ while (!dq .isEmpty ()) {
33+ int [] curr = dq .poll ();
34+ int y = curr [0 ];
35+ int x = curr [1 ];
36+ int moves = curr [2 ];
37+ long currWeight = weight [y ][x ][moves ];
38+
39+ if (moves == maxMove ) continue ;
40+
41+ for (int dir =0 ; dir <4 ; dir ++) {
42+ int ny = y + dy [dir ];
43+ int nx = x + dx [dir ];
44+
45+ if (ny < 0 || nx < 0 || ny >= m || nx >=n ) ans =(ans +currWeight )%MOD ;
46+ else {
47+ weight [ny ][nx ][moves +1 ] = (weight [ny ][nx ][moves +1 ] + currWeight )%MOD ;
48+
49+ if (!visited [ny ][nx ][moves +1 ]) {
50+ visited [ny ][nx ][moves +1 ] = true ;
51+ dq .add (new int []{ny ,nx ,moves +1 });
52+ }
53+ }
54+ }
55+ }
56+
57+ return (int )ans ;
58+ }
59+ }
0 commit comments