반응형
이전에 포스팅 했던 탐색알고리즘 중 깊이 우선 탐색 알고리즘에 대해 포스팅하려고합니다.
우선 알고리즘 문제는 NHN 채용사이트에서 공개된 Pre-Test 문제를 참고했습니다.
문제가 된다면 다른 알고리즘 문제로 대체하도록 하겠습니다.
문제출처: https://recruit.nhn.com/pdf/%ED%94%84%EB%A6%AC%ED%85%8C%EC%8A%A4%ED%8A%B8_1%EC%B0%A8_%EA%B8%B0%EC%B6%9C%EB%AC%B8%EC%A0%9C.pdf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
public class PreTest {
static int[] x = {-1, 1, 0, 0};
static int[] y = {0, 0, -1, 1};
static int[][] rowCol;
static int index;
static int tmp;
static boolean[][] visitRowCol;
public static void main(String[] args) {
preOne();
}
private static void preOne() {
int cnt = 0;
List<Integer> resList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
index = sc.nextInt();
rowCol = new int[index][index];
visitRowCol = new boolean[index][index];
for(int i=0; i<index; i++) {
for(int j=0; j<index; j++) {
rowCol[i][j] = sc.nextInt();
}
}
for(int i=0; i<index; i++) {
for(int j=0; j<index; j++) {
if(rowCol[i][j] == 1 && !visitRowCol[i][j]) {
tmp = 1;
dfs(i, j);
cnt++;
resList.add(tmp);
}
}
}
System.out.println(cnt);
Collections.sort(resList);
for(int i: resList) {
System.out.print(i + " ");
}
}
private static void dfs(int row, int col) {
visitRowCol[row][col] = true;
for(int i=0; i<4; i++) {
if( row + x[i] >= 0 &&
col + y[i] >= 0 &&
row + x[i] < index &&
col + y[i] < index) {
if( rowCol[row + x[i]][col + y[i]] == 1 &&
!visitRowCol[row+x[i]][col+y[i]] ) {
tmp++;
dfs(row + x[i], col + y[i]);
}
}
}
}
}
|
반응형
'- others' 카테고리의 다른 글
Cloud Native Application 고려사항 (0) | 2021.05.06 |
---|---|
Gradle Multi Module 프로젝트 생성 (0) | 2021.05.01 |
[탐색알고리즘] 깊이 우선 탐색, 너비 우선 탐색 (0) | 2020.11.16 |
[Bash] jar파일 실행, 외부 설정파일 사용 (0) | 2020.10.29 |
[Kafka] Java 테스트 애플리케이션 제작 및 테스트 (0) | 2020.10.28 |