https://www.acmicpc.net/problem/11403
11403번: 경로 찾기
가중치 없는 방향 그래프 G가 주어졌을 때, 모든 정점 (i, j)에 대해서, i에서 j로 가는 경로가 있는지 없는지 구하는 프로그램을 작성하시오.
www.acmicpc.net
문제 : 가중치 없는 방향 그래프 G가 주어졌을 때, 모든 정점 (i, j)에 대해서, i에서 j로 가는 경로가 있는지 없는지 구하는 프로그램을 작성하시오. 풀이 : 0 1 0 0 0 1 1 0 0 일 때, 0->1 / 1-> 2 / 2-> 0 이므로 0->1->2->0 으로 접근이 가능합니다. (1->2->0, 2->1->0) bfs 활용해서 접근 가능하면 1, 그렇지 않다면 0 으로 출력합니다. |
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int N;
static int[][] map;
static boolean[] visited;
static Queue<Integer> queue;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
map = new int[N][N];
queue = new LinkedList();
visited = new boolean[N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
map[i][j] = sc.nextInt();
}
}
// end of input
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(map[i][j] + " ");
}
System.out.println();
}
}
public static void bfs(int i) {
queue.offer(i);
while(!queue.isEmpty()) {
int temp = queue.poll();
for (int j = 0; j < N; j++) {
if(map[temp][j]==1 && !visited[j]) {
map[i][j] = 1;
queue.offer(j);
visited[j] = true;
}
}
}
}
}
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
[백준] 1389번 케빈 베이컨의 6단계 법칙 (0) | 2020.08.03 |
---|---|
[백준] 9372번 상근이의 여행 (0) | 2020.07.29 |
[백준] 7562번 나이트의 이동 (0) | 2020.07.28 |
[백준] 2644번 촌수계산 (0) | 2020.06.26 |
[프로그래머스] 전화번호 목록 (0) | 2020.06.20 |