접근 방법
문제 제목에서도 알 수 있듯이 단순하게 DFS와 BFS를 구현하면 된다.
DFS와 BFS에 대해서는 이전에 정리한 글을 참고하자.
https://edvedv.tistory.com/4?category=1038364
백준 BOJ 1012번
접근 방법 인접한 배추들을 그래프 형태로 생각하면, DFS와 BFS를 사용하여 문제를 풀 수 있다. DFS, BFS 둘다 그래프를 탐색하는 방법이다. 그래프란, 정점(node)과 그 정점을 연결하는 간선(edge)으로
edvedv.tistory.com
하나 주의할 점이 있다면, 입력에서 좌표를 그대로 받기 위해서 간선을 저장하는 배열의 길이를 N+1로 한다는 점.
코드
import java.util.*;
public class Main {
static int edge[][];
static boolean visit[];
static int N, M;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
N = in.nextInt();
M = in.nextInt();
int V = in.nextInt();
edge = new int[N+1][N+1];
visit = new boolean[N+1];
for(int i = 0; i < M; i++){
int x = in.nextInt();
int y = in.nextInt();
edge[x][y] = 1;
edge[y][x] = 1;
}
dfs(V);
visit = new boolean[N+1];
System.out.println();
bfs(V);
in.close();
}
public static void dfs(int v){
visit[v] = true;
System.out.print(v + " ");
for(int i = 1; i <= N; i++){
if(edge[v][i] == 1 && visit[i] == false)
dfs(i);
}
}
public static void bfs(int v){
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(v);
visit[v] = true;
System.out.print(v + " ");
while(!queue.isEmpty()){
int temp = queue.poll();
for(int i = 0; i <= N; i++){
if(edge[temp][i] == 1 && visit[i] == false) {
queue.offer(i);
visit[i] = true;
System.out.print(i + " ");
}
}
}
}
}
'알고리즘 > Class 3' 카테고리의 다른 글
백준 BOJ 1463번 (0) | 2022.08.16 |
---|---|
백준 BOJ 1389번 (0) | 2022.08.16 |
백준 BOJ 1107번 (0) | 2022.08.15 |
백준 BOJ 1074번 (0) | 2022.08.11 |
백준 BOJ 1012번 (0) | 2022.08.09 |
댓글