접근 방법
DFS와 BFS 둘 다 사용할 수 있는 문제다. DFS, BFS를 활용할 줄 안다면 쉽게 풀 수 있는 문제다.
필자는 BFS를 사용해서 풀었다.
DFS, BFS를 정리해놓은 글이다.
https://edvedv.tistory.com/4?category=1038364
백준 BOJ 1012번
접근 방법 인접한 배추들을 그래프 형태로 생각하면, DFS와 BFS를 사용하여 문제를 풀 수 있다. DFS, BFS 둘다 그래프를 탐색하는 방법이다. 그래프란, 정점(node)과 그 정점을 연결하는 간선(edge)으로
edvedv.tistory.com
// Class 3에는 bfs가 굉장히 많은 느낌
코드
import java.util.*;
public class Main {
static int node[][];
static boolean visit[];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int M = in.nextInt();
node = new int[N+1][N+1];
visit = new boolean[N+1];
for(int i = 0 ;i < M ;i++) {
int a = in.nextInt();
int b = in.nextInt();
node[a][b] = node[b][a] = 1;
}
bfs(1);
}
static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
visit[start] = true;
q.offer(start);
int count = 0;
while(!q.isEmpty()) {
int temp = q.poll();
for(int i = 1; i < node.length; i++) {
if(node[temp][i] == 1 && !visit[i]) {
q.offer(i);
visit[i] = true;
count++;
}
}
}
System.out.println(count);
}
}
'알고리즘 > Class 3' 카테고리의 다른 글
백준 BOJ 2667번 - 단지번호붙이기 (0) | 2022.08.31 |
---|---|
백준 BOJ 2630번 - 색종이 만들기 (0) | 2022.08.31 |
백준 BOJ 2579번 - 계단 오르기 (0) | 2022.08.29 |
백준 BOJ 2178번 - 미로 탐색 (0) | 2022.08.28 |
백준 BOJ 1992번 (0) | 2022.08.22 |
댓글