https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. (
www.acmicpc.net
1. 풀이
이 문제 역시 DFS를 통해서 문제를 풀이합니다.
주의할 점은 2차원 배열의 가로와 세로의 위치를 잘 지정해줘야하는 것입니다.
2. 코드
import java.util.*;
public class Main {
static int[][] map = new int[51][51];
static int width; // 가로
static int height; // 세로
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,1,-1};
static int count = 0; // 배추흰지렁이 카운트.
static void dfs(int i, int j) {
map[i][j] = 0; // 방문 체크
for(int k = 0; k < 4; k++) {
if(i + dy[k] < 0 || i + dy[k] >= height || j + dx[k] < 0 || j + dx[k] >= width)
continue;
if(map[i+dy[k]][j+dx[k]] == 1) {
dfs(i+dy[k],j+dx[k]);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> result = new ArrayList<Integer>();
int numOfTest = sc.nextInt();
int numOfLocation;
for(int i = 0; i < numOfTest; i++) {
width = sc.nextInt();
height = sc.nextInt();
numOfLocation = sc.nextInt();
// 배추의 위치 입력.
for(int j = 0 ; j < numOfLocation; j++) {
int w = sc.nextInt();
int h = sc.nextInt();
map[h][w] = 1;
}
// 배추 위치를 찾으면 해당 배추 위치를 시작점으로 dfs
for(int h = 0; h < height; h++) {
for(int w = 0; w < width; w++) {
if(map[h][w] == 1) {
dfs(h,w);
count++;
}
}
}
result.add(count);
count = 0;
}
for(int i = 0; i < result.size(); i++)
System.out.println(result.get(i));
sc.close();
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준 1463] 1로 만들기 - 자바 (0) | 2020.04.01 |
---|---|
[백준 14502]연구소 - 자바 (0) | 2020.03.31 |
[백준 11724]연결 요소의 개수 - 자바 (0) | 2020.03.31 |
[백준 11403] 경로 찾기 - 자바 (0) | 2020.03.31 |
[백준 2667]단지번호붙이기 - 자바 (0) | 2020.03.30 |
댓글