-
[백준] 토마토 - 7576알고리즘 문제 풀이/백준 2021. 4. 16. 09:13
문제설명
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
기본아이디어
정말 정석적인 BFS 탐색 문제입니다. 익은 토마토를 찾아서 주변 네방향으로 안익은 토마토를 찾으면 익은 상태로 만들고 다음에 새로 익은 토마토 기준으로 반복하면 된다.
구현코드
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061public static void main(String[] args) throws IOException {StringTokenizer st = new StringTokenizer(input.readLine());M = Integer.parseInt(st.nextToken());N = Integer.parseInt(st.nextToken());map = new int[N][];int r = 0;int c = 0;for(int i = 0; i < N; i++){st = new StringTokenizer(input.readLine());int[] temp = new int[M];for(int j = 0; j < M; j++) {temp[j] = Integer.parseInt(st.nextToken());}map[i] = temp;}System.out.println(bfs());}static int N,M;static int[][] map;static int[] dr = {1, -1, 0, 0};static int[] dc = {0, 0, -1, 1};static int bfs(){int result = -1;Queue<int[]> queue = new LinkedList<>();for(int i = 0; i < N; i++){for(int j = 0; j < M; j++){if(map[i][j] == 1)queue.add(new int[]{i,j});}}while (!queue.isEmpty()){int size = queue.size();result++;for(int i = 0; i < size; i++) {int[] loc = queue.poll();for (int d = 0; d < 4; d++) {int nr = loc[0] + dr[d];int nc = loc[1] + dc[d];if (isIn(nr, nc) && map[nr][nc] == 0) {map[nr][nc] = 1;queue.add(new int[]{nr, nc});}}}}for(int i = 0; i < N; i++){for(int j = 0; j < M; j++){if(map[i][j] == 0)return -1;}}return result;}static boolean isIn(int r, int c){return r >= 0 && r < N && c >= 0 && c < M;}cs 정리, 기억할 내용
1. BFS 탐색!!
'알고리즘 문제 풀이 > 백준' 카테고리의 다른 글
[백준] 아기 상어 - 16236번 (0) 2021.04.16 [백준] 직사각형 탈출 - 16973번 (0) 2021.04.16 [백준] 달이 차오른다, 가자. - 1194 (0) 2021.04.14 [백준] 카드 구매하기 - 11052 (0) 2021.04.14 [백준] 경비원 - 2564 (0) 2021.04.13