반응형
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[][] graph;
static boolean visited[];
static int N;
static int M;
static int start;
public static void dfs(int i) {
visited[i] = true;
System.out.print(i + " ");
for (int j = 1; j <= N; j++) {
if (graph[i][j] == 1 && visited[j] == false) {
dfs(j);
}
}
}
public static void bfs(int i) {
Queue<Integer> q = new LinkedList<Integer>();
q.offer(i);
visited[i] = true;
System.out.print(i + " ");
int tmp;
while(!q.isEmpty()) {
tmp = q.poll();
for (int j = 1; j <= N; j++) {
if (graph[tmp][j] == 1 && visited[j] == false) {
q.offer(j);
visited[j] = true;
System.out.print(j + " ");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
start = sc.nextInt();
graph = new int[1001][1001];
visited = new boolean[1001];
int a,b;
for (int i = 0; i < M; i++) {
a = sc.nextInt();
b = sc.nextInt();
graph[a][b] = graph[b][a] = 1;
}
dfs(start);
for (int i = 1; i <= N; i++) {
visited[i] = false;
}
System.out.println();
bfs(start);
}
}
반응형
LIST
'알고리즘 > 연습문제' 카테고리의 다른 글
백준 - 11399 ATM(feat. java) (0) | 2019.08.13 |
---|---|
백준 - 7576 토마토(feat. java) (0) | 2019.08.12 |
백준 2667 - 단지번호 붙이기(feat. java) (0) | 2019.08.12 |
백준 - 1697 숨바꼭질(feat. java) (0) | 2019.08.12 |
백준 2178 - 미로찾기(feat. java) (0) | 2019.08.12 |