🌞Algorithm/🔥Baekjoon

[Baekjoon] 16390_Sheba’s Amoebas

뿌야._. 2024. 11. 14. 18:08
문제(출처: https://www.acmicpc.net/problem/16390)

< Sheba's Amoebas >

 

문제 풀이 

 

bfs 알고리즘을 활용한다.

 

 my solution (Java)

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 _16390_ { // Sheba’s Amoebas
	static boolean arr[][];
	static int dx[] = { -1, 1, 0, 0, -1, -1, 1, 1 };
	static int dy[] = { 0, 0, -1, 1, -1, 1, -1, 1 };
	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(bf.readLine());
		int m = Integer.parseInt(st.nextToken());
		int n = Integer.parseInt(st.nextToken());
		arr = new boolean[m][n];
		for (int i = 0; i < m; i++) {
			String str = bf.readLine();
			for (int j = 0; j < n; j++) {
				if (str.charAt(j) == '#') {
					arr[i][j] = true;
				}
			}
		}
		int result = 0;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (arr[i][j]) {
					result += 1;
					bfs(i, j);
				}
			}
		}
		System.out.println(result);
	}
	private static void bfs(int i, int j) {
		Queue<int[]> queue = new LinkedList<>();
		queue.add(new int[] { i, j });
		arr[i][j] = false;
		while (!queue.isEmpty()) {
			int temp[] = queue.poll();
			for (int k = 0; k < 8; k++) {
				int x = temp[0] + dx[k];
				int y = temp[1] + dy[k];
				if (x >= 0 && x < arr.length && y >= 0 && y < arr[0].length && arr[x][y]) {
					arr[x][y] = false;
					queue.add(new int[] { x, y });
				}
			}
		}
	}
}
변수)
m, n : 배열 크기
arr : 배열 정보
result : 정답

 

배열 크기를 입력받아 배열 크기만큼 정보를 입력받는다. 값이 #라면 배열을 true로 저장한다. 배열을 전체 탐색하며 true라면 result+1 및 bfs 함수를 호출한다.

최종 result를 출력한다.

 

bfs(int i, int j)

Queue에 시작 위치를 저장하며 시작 위치를 false로 저장한다. Queue가 빌 때까지 다음 과정을 반복한다.

1) Queue poll

2) 8방향으로 탐색 후 배열 범위 안이며 배열 값이 true라면 false로 저장 및 Queue에 추가한다.

 



 

'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글

[Baekjoon] 6798_Knight Hop  (0) 2024.11.18
[Baekjoon] 15242_Knight  (1) 2024.11.15
[Baekjoon] 5931_Cow Beauty Pageant  (0) 2024.11.13
[Baekjoon] 8061_Bitmap  (0) 2024.11.12
[Baekjoon] 15092_Sheba’s Amoebas  (1) 2024.11.11