Algorithm

BOJ 1260 DFS BFS

VanDevKIM 2018. 11. 6. 12:42


import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

static ArrayList<Integer>[] adj;
static boolean[] visited;

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int start = sc.nextInt();

adj = (ArrayList<Integer>[]) new ArrayList[N+1];
for(int i=1; i<=N ;i++){
adj[i] = new ArrayList<Integer>();
}

//input adj
for(int i=0; i<M; i++){
int u = sc.nextInt();
int v = sc.nextInt();
adj[u].add(v);
adj[v].add(u);
}

for(int i=1; i<=N; i++){
Collections.sort(adj[i]);
}

visited = new boolean[N+1];
dfs(start);

System.out.println();
visited = new boolean[N+1];
bfs(start);

}

private static void dfs(int x) {
if(visited[x]) return;
visited[x] = true;
System.out.print(x + " ");
for(int y : adj[x]){
if(!visited[y])
dfs(y);
}
}
private static void bfs(int start){
Queue<Integer> q = new LinkedList<>();
q.add(start);
visited[start] = true;
while(!q.isEmpty()) {
int x = q.remove();
System.out.print(x + " ");
for(int y : adj[x]){
if(!visited[y]){
visited[y] = true;
q.add(y);
}
}
}
}
}


<Result>

4 5 1

1 2 

1 3

1 4

2 4

3 4

1 2 4 3 

1 2 3 4