Skip to content

Commit c361043

Browse files
Merge pull request #1695 from CodingTestStudy2/이진희
[이진희] Day22
2 parents cffbc86 + 8948c48 commit c361043

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
3+
1. 아이디어 : 각 정점의 개수 구하기
4+
5+
2. 시간복잡도 : O(N^2)
6+
7+
3. 자료구조/알고리즘 : 완전탐색
8+
9+
*/
10+
11+
class Solution {
12+
public int[] findDegrees(int[][] matrix) {
13+
int n = matrix[0].length;
14+
15+
int ans[] = new int[n];
16+
for(int k=0; k<n; k++) {
17+
for(int i=0; i<n; i++) {
18+
if(matrix[k][i] == 0) continue;
19+
ans[k]++;
20+
}
21+
}
22+
return ans;
23+
}
24+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)