-
백준 1012번 유기농 배추(자바) - DFS, BFS코딩테스트 2022. 1. 7. 15:10
유기농 배추
시간 제한메모리 제한제출정답맞힌 사람정답 비율1 초 512 MB 92423 35443 23991 36.581% 문제
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. 한 배추의 상하좌우 네 방향에 다른 배추가 위치한 경우에 서로 인접해있는 것이다.
한나가 배추를 재배하는 땅은 고르지 못해서 배추를 군데군데 심어 놓았다. 배추들이 모여있는 곳에는 배추흰지렁이가 한 마리만 있으면 되므로 서로 인접해있는 배추들이 몇 군데에 퍼져있는지 조사하면 총 몇 마리의 지렁이가 필요한지 알 수 있다. 예를 들어 배추밭이 아래와 같이 구성되어 있으면 최소 5마리의 배추흰지렁이가 필요하다. 0은 배추가 심어져 있지 않은 땅이고, 1은 배추가 심어져 있는 땅을 나타낸다.
1 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 1 1 0 0 0 0 1 0 0 1 1 1 입력
입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 그 다음 줄부터 각각의 테스트 케이스에 대해 첫째 줄에는 배추를 심은 배추밭의 가로길이 M(1 ≤ M ≤ 50)과 세로길이 N(1 ≤ N ≤ 50), 그리고 배추가 심어져 있는 위치의 개수 K(1 ≤ K ≤ 2500)이 주어진다. 그 다음 K줄에는 배추의 위치 X(0 ≤ X ≤ M-1), Y(0 ≤ Y ≤ N-1)가 주어진다. 두 배추의 위치가 같은 경우는 없다.
출력
각 테스트 케이스에 대해 필요한 최소의 배추흰지렁이 마리 수를 출력한다.
예제 입력 1 복사
2 10 8 17 0 0 1 0 1 1 4 2 4 3 4 5 2 4 3 4 7 4 8 4 9 4 7 5 8 5 9 5 7 6 8 6 9 6 10 10 1 5 5
예제 출력 1 복사
5 1
예제 입력 2 복사
1 5 3 6 0 2 1 2 2 2 3 2 4 2 4 0
예제 출력 2 복사
2
주의할 점
1. 새로운 테스트 케이스 실행할 때마다 count는 초기화 되어야 한다.
2. 한 점에서 상하좌우를 모두 탐색하므로 index가 -1이 되거나 m-1이나 n-1의 값보다 큰 경우가 발생한다.
3. Queue<Integer> 형식을 사용하면 숫자 하나만 큐에 넣을 수 있으므로 Queue<Point> 형식으로 Point 클래스를 만들어 (x,y) 값을 큐에 넣을 수 있도록 하자.
1. BFS
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { static int[][] location; static boolean[][] visited; static int[] dx = {-1,0,1,0}; static int[] dy = {0,-1,0,1}; static int count; public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); for (int i = 0; i < t; i++){ count = 0; st = new StringTokenizer(br.readLine()); int m = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); location = new int[m+1][n+1]; visited = new boolean[m+1][n+1]; for (int j = 0; j < k; j++) { st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); location[x][y] = 1; } for (int j = 0; j < m; j++) { for (int g = 0; g < n; g++) { if (location[j][g] == 1 && !visited[j][g]) { bfs(j,g); } } } System.out.println(count); } } static void bfs(int j, int g) { Queue<Point> queue = new LinkedList<>(); queue.offer(new Point(j, g)); visited[j][g] = true; count++; while (!queue.isEmpty()) { Point point = queue.poll(); for (int i = 0; i < 4; i++) { int x = point.x + dx[i]; int y = point.y + dy[i]; if (x>=0 && y>=0 && location[x][y] == 1 && !visited[x][y]) { queue.offer(new Point(x,y)); visited[x][y] = true; } } } } static class Point{ int x; int y; Point(int x, int y) { this.x = x; this.y = y; } } }
2. DFS
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { static int[][] location; static boolean[][] visited; static int[] dx = {-1,0,1,0}; static int[] dy = {0,-1,0,1}; static int count; public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); for (int i = 0; i < t; i++){ count = 0; st = new StringTokenizer(br.readLine()); int m = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); location = new int[m+1][n+1]; visited = new boolean[m+1][n+1]; for (int j = 0; j < k; j++) { st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); location[x][y] = 1; } for (int j = 0; j < m; j++) { for (int g = 0; g < n; g++) { if (location[j][g] == 1 && !visited[j][g]) { count++; dfs(j,g); } } } System.out.println(count); } } static void dfs(int j, int g) { visited[j][g] = true; for (int i = 0; i < 4; i++) { int x = j + dx[i]; int y = g + dy[i]; if (x>=0 && y>=0 && location[x][y] == 1 && !visited[x][y]) { visited[x][y] = true; dfs(x,y); } } } }
'코딩테스트' 카테고리의 다른 글
백준 1697번 숨바꼭질(자바) - BFS (0) 2022.01.09 백준 7576번 토마토(자바) -BFS* (0) 2022.01.07 백준 1707번 이분 그래프(자바) - DFS* (0) 2021.12.24 백준 11724번 연결 요소의 개수(자바) - DFS (0) 2021.11.23 백준 1744 수 묶기(자바) - 그리디 (0) 2021.11.12