Jun's Development Journey
[BOJ] 11403번 경로 찾기 본문
문제
https://www.acmicpc.net/problem/11403
11403번: 경로 찾기
가중치 없는 방향 그래프 G가 주어졌을 때, 모든 정점 (i, j)에 대해서, i에서 j로 가는 경로가 있는지 없는지 구하는 프로그램을 작성하시오.
www.acmicpc.net
풀이
이 문제를 처음 접근할 때는 각 시점과 목적점을 사용하여 DFS로 풀었었다. 하지만 실행시간이 오래 걸리고, 메모리도 많이 쓰는 방식을 썼던 것 같아서 다른 방법을 찾던 중 다른 분이 포스팅했던 글을 보고 Floyd-Warshall 알고리즘을 이용하여 갈 수 있는 방법을 초기화해주는 방식으로 하면 실행시간을 줄일 수 있는 것을 알게 되었다.
1) DFS
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
|
public class Main {
static Scanner scan = new Scanner(System.in);
static int[][] array;
static boolean[] visited;
static boolean flag;
static int N;
static void solution() {
N = scan.nextInt();
array = new int[N][N];
visited = new boolean[N];
//입력
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++)
array[i][j] = scan.nextInt();
}
//계산
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
reset_visit();
flag = false;
dfs(i,j);
if(flag)
System.out.print("1 ");
else
System.out.print("0 ");
}
System.out.println();
}
}
static void dfs(int from, int dest) {
for(int i=0;i<N;i++) {
if(array[from][i] == 1 && !visited[i]) {
if(i==dest) {
flag = true;
return;
}
visited[i] = true;
dfs(i,dest);
}
}
}
static void reset_visit() {
for(int i=0;i<N;i++)
visited[i] = false;
}
public static void main(String[] args) {
solution();
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
2
2) Floyd-Warshall
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
|
public class Main {
static Scanner scan = new Scanner(System.in);
static int[][] array;
static int N;
static void solution() {
N = scan.nextInt();
array = new int[N][N];
//입력
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++)
array[i][j] = scan.nextInt();
}
//계산
for(int p = 0;p<N;p++) {
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++) {
if(array[i][p]==1 && array[p][j] == 1)
array[i][j] = 1;
}
}
}
//출력
for(int i=0;i<N;i++) {
for(int j=0;j<N;j++)
System.out.print(array[i][j]+" ");
System.out.println();
}
}
public static void main(String[] args) {
solution();
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
'BOJ > DFS' 카테고리의 다른 글
[BOJ] 1260 DFS, BFS (0) | 2021.02.26 |
---|---|
[BOJ] 2644 촌수계산 (0) | 2021.02.23 |
[BOJ] 2606번 바이러스 (0) | 2021.02.18 |
[BOJ] 11724번 연결 요소의 갯수 (0) | 2019.08.30 |
[BOJ] 14502번 연구소 (0) | 2019.07.30 |