https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. (
www.acmicpc.net
목표 : 2차원 배열에서 배추가 심어져 있는 땅에 지렁이가 총 몇마리 필요한지 구하기
|
import java.util.Arrays;
import java.util.Scanner;
//유기농 배추
public class Main {
static int T, M, N, K, count = 0;
static int[][] map, dir = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
static boolean[][] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
T = sc.nextInt();
for (int tc = 1; tc <= T; tc++) {
N = sc.nextInt();
M = sc.nextInt();
K = sc.nextInt();
map = new int[N][M];
visited = new boolean[N][M];
for (int k = 0; k < K; k++) {
int x = sc.nextInt();
int y = sc.nextInt();
map[x][y] = 1;
} // end of input
// for (int i = 0; i < N; i++) {
// System.out.println(Arrays.toString(map[i]));
// }
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 1 && !visited[i][j]) {
dfs(i, j);
count++;
}
}
}
System.out.println(count);
visited = new boolean[N][M];
count=0;
} // end of tc
}// end of main
public static void dfs(int x, int y) {
visited[x][y] = true;
for (int k = 0; k < 4; k++) {
int nx = x + dir[k][0];
int ny = y + dir[k][1];
if (isInside(nx, ny) && map[nx][ny] == 1 && !visited[nx][ny]) {
dfs(nx, ny);
}
}
}
public static boolean isInside(int x, int y) {
return x >= 0 && x < N && y >= 0 && y < M;
}
}
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
[백준] 2178번 미로탐색 (0) | 2020.04.01 |
---|---|
[백준] 2630번 색종이 만들기 (0) | 2020.04.01 |
[백준] 2468번 안전영역 (0) | 2020.04.01 |
[백준] 7576 토마토 (0) | 2020.03.31 |
[백준] 1260번 DFS와 BFS (0) | 2020.03.31 |