🌞Algorithm/🔥Baekjoon

[Baekjoon] 5993_Invasion of the Milkweed

뿌야._. 2024. 10. 11. 14:56
문제(출처: https://www.acmicpc.net/problem/5993)

< Invasion of the Milkweed >

 

문제 풀이 

 

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 _5993_ { // Invasion of the Milkweed
	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 X = Integer.parseInt(st.nextToken());
		int Y = Integer.parseInt(st.nextToken());
		int Mx = Integer.parseInt(st.nextToken());
		int My = Integer.parseInt(st.nextToken());
		arr = new boolean[Y][X];
		for (int i = 0; i < Y; i++) {
			String str = bf.readLine();
			for (int j = 0; j < X; j++) {
				if (str.charAt(j) == '*') {
					arr[i][j] = true;
				}
			}
		}
		System.out.println(bfs(Y - My, Mx - 1));
	}
	private static int bfs(int i, int j) {
		Queue<int[]> queue = new LinkedList<>();
		queue.add(new int[] { i, j, 0 });
		arr[i][j] = true;
		int result = 0;
		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] = true;
					result = Math.max(result, temp[2] + 1);
					queue.add(new int[] { x, y, temp[2] + 1 });
				}
			}
		}
		return result;
	}
}
변수)
X, Y, Mx, My : 배열 크기, 시작 위치
arr : 배열 정보
dx, dy : 상, 하, 좌, 우, 대각선

 

배열 크기와 시작 위치를 입력받는다. 배열 크기만큼 배열 정보를 입력받아 *라면 true로 저장한다. bfs를 호출하여 반환 값을 출력한다.

 

bfs(시작 위치)

큐에 시작 좌표와 이동 횟수를 저장한 후 큐가 빌 때까지 다음 과정을 반복한다.

 

1) queue poll

2) 8방향을 탐색하며 배열 범위 안이며 아직 방문하지 않은 곳이라면 방문 표시와 result 값을 최댓값으로 업데이트 및 queue에 추가

 

최종 result를 반환한다.



 

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

[Baekjoon] 8598_Zając  (0) 2024.10.18
[Baekjoon] 30610_A-maze-ing Lakes  (0) 2024.10.17
[Baekjoon] 9781_Knight Moves  (0) 2024.10.10
[Baekjoon] 9700_RAINFOREST CANOPY  (2) 2024.10.08
[Baekjoon] 9790_Elephant Show  (0) 2024.10.07