문제 링크 : https://www.acmicpc.net/problem/11403


1. 인접행렬을 입력받고 결과를 기록할 2차원배열 result를 생성


2. 정점의 갯수반큼 반복

각 정점별로 bfs 샐행하며 한정점에서 갈수있는 정점을 result 배열에 표시.


3. result 배열 출력


이렇게 풀었다. 그래프 캄색에는 bfs를 사용하였다.


주의 할 점이 있는데 한 정점에서 자기자신은 그냥 바로 1을 체크 하는것이 아니고, 다른 정점을 거쳐서 방문이 가능한 경우에만 1로 체크해주어야 한다.



아래는 소스코드이다.


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
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
    static int n;
    static boolean[] visited;
    static int[][] injub;
    static int[][] result;
    
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        injub = new int[n][n];
        result = new int[n][n];
        
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                injub[i][j] = sc.nextInt();
            }
        }
        
        for(int i=0; i<n; i++) {
            visited = new boolean[n];
            bfs(i);
        }
        
        
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
        
    }
    
    static public void bfs(int start) {
        
        Queue<Integer> q = new LinkedList<Integer>();
        q.offer(start);
        
        while(!q.isEmpty()) {
            int current = q.poll();
            
            for(int i=0; i<n; i++) {
                if(injub[current][i]==1 && visited[i]==false) {
                    visited[i] = true;
                    q.offer(i);
                    result[start][i] = 1;
                }
            }
        }
    }
    
}
 
cs



'Algorithm > 백준' 카테고리의 다른 글

백준 6603번 로또  (0) 2019.01.14
백준 1987번 알파벳  (0) 2019.01.05
백준 11724번 연결 요소의 개수  (0) 2019.01.02
백준 2583번 영역구하기  (0) 2018.12.31
백준 2468번 안전영역  (0) 2018.12.28

+ Recent posts