그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
package com.DFS_BFS;
import java.util.Scanner;
public class BOJ1260 {
//1. 클래스 변수로 선언
public static int[][]graph; //이차원 배열 graph
public static boolean[]visited; //방문확인용 boolean타입의 visited
public static int n; //정점의 개수 n
public static int m; //간선의 개수 m
public static int start; //시작점 start
public static void dfs(int i){
//7. 매개변수로 들어온 값(정점)에 해당하는 visited 방문처리를 위해 true
visited[i] = true;
//8. 방문한 정점 출력
System.out.print(i + " ");
//9. 정점과 연결된 다른 정점 확인
for(int j = 1;j<=n;j++){
//10. 정점에 연결이 되어있고( = 값이 1이고) 방문하지 않았다면 dsf 재귀호출
if(graph[i][j] == 1 && visited[j] == false){
dfs(j);
}
}
}
public static void main(String[] args) {
//2. 입력받기
Scanner sc = new Scanner(System.in);
n = sc.nextInt();//정점의 개수
m = sc.nextInt();//간선의 개수
start = sc.nextInt();//시작정점 번호
//3.graph 초기화
graph = new int[n+1][n+1];
//4. 방문체크용 visited 초기화
visited = new boolean[n+1];
//5. 연결된 정점 연결해주기
for(int i = 0;i<m;i++){
int x = sc.nextInt();
int y = sc.nextInt();
//5.1 1로 서로 연결해주기(둘다 연결해줘야함 , 정점1 과 정점2는 서로 연결되어 //있기때문)
graph[x][y] = graph[y][x] = 1;
}
//6. dfs 호출
dfs(start);
}
}
package com.DFS_BFS;
import java.util.ArrayList;
import java.util.Scanner;
public class BOJ1260_2 {
//1.방문을 확인할 boolean타입의 visited 배열과
// 이중 ArrayList형의 graph를 클래스 변수로 선언
public static boolean[]visited;
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
public static void dfs(int x){
//7. 받아온 정점의 번호 방문처리를 위해 true
visited[x] = true;
//8. 방문한 정점은 출력
System.out.print(x + " ");
//9.받아온 정점에서 연결된 다른 정점 확인하기
for(int i = 0;i<graph.get(x).size();i++){
int y = graph.get(x).get(i);
//10. 정점에 연결된 다른 정점중 방문처리가 안되어있다면 dfs 재귀실행
if(!visited[y]) dfs(y);
}
}
public static void main(String[] args) {
//2. 입력값 받기
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//정점의 개수
int m = sc.nextInt();//간선의 개수
int start = sc.nextInt();//시작정점 번호
//3. visited 배열 초기화
visited = new boolean[n+1];
//4. 그래프 초기화
for(int i = 0;i<n+1;i++){
graph.add(new ArrayList<Integer>());
}
//5. graph 정점에 간선 연결해주기 (1번노드와 2번 노드가 연결되어있다면
// 1 -> 2 , 2 -> 1 로 서로 연결해주어야함)
for(int i = 0;i<m;i++){
int x = sc.nextInt();
int y = sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
//6. dfs 에 시작번호 넣어주기
dfs(start);
}
}
BFS로도 공부해서 추가적으로 올릴 계획이다!