ALGORITHM/프로그래머스 | 백준 | 삼성 | 카카오

[백준] 1012번 유기농 배추

SZCODE 2020. 4. 1. 00:16

https://www.acmicpc.net/problem/1012

 

1012번: 유기농 배추

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 효과적인 배추흰지렁이를 구입하기로 결심한다. 이 지렁이는 배추근처에 서식하며 해충을 잡아 먹음으로써 배추를 보호한다. 특히, 어떤 배추에 배추흰지렁이가 한 마리라도 살고 있으면 이 지렁이는 인접한 다른 배추로 이동할 수 있어, 그 배추들 역시 해충으로부터 보호받을 수 있다. (

www.acmicpc.net

목표 : 2차원 배열에서 배추가 심어져 있는 땅에 지렁이가 총 몇마리 필요한지 구하기


1은 배추가 심어져있는 땅이고 인접한 배추들은 1마리의 지렁이만 필요하다. 
DFS 활용 
count 변수를 활용해 지렁이 개수를 세줌 
주의할 부분은 방문처리와 count 변수를 초기화 해주는 것

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;
	}

}