🌞Algorithm/🔥Baekjoon

[Baekjoon] 32813_Oooh I See

뿌야._. 2026. 4. 24. 11:49
문제(출처: https://www.acmicpc.net/problem/32813)

< Oooh I See >

 

문제 풀이 

 

모든 칸을 탐색하며 인접한 8칸에 'O'가 있다면 ArrayList에 저장한다. ArrayList의 size에 따라 답을 출력한다.  

 

my solution (Java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class _32813_ { // Oooh I See

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st = new StringTokenizer(bf.readLine());

		int r = Integer.parseInt(st.nextToken());
		int c = Integer.parseInt(st.nextToken());

		char arr[][] = new char[r][c];

		for (int i = 0; i < r; i++) {
			String str = bf.readLine();
			for (int j = 0; j < c; j++) {
				arr[i][j] = str.charAt(j);
			}
		}

		int dx[] = { -1, 1, 0, 0, -1, -1, 1, 1 };
		int dy[] = { 0, 0, -1, 1, -1, 1, -1, 1 };

		ArrayList<int[]> list = new ArrayList<>();

		for (int i = 0; i < r; i++) {
			for (int j = 0; j < c; j++) {
				if (Character.isAlphabetic(arr[i][j])) {
					continue;
				}
				int cnt = 0;
				for (int k = 0; k < 8; k++) {
					int x = i + dx[k];
					int y = j + dy[k];
					if (x >= 0 && x < r && y >= 0 && y < c) {
						if (arr[x][y] == 'O') {
							cnt += 1;
						}
					}
				}
				if (cnt == 8) {
					list.add(new int[] { i + 1, j + 1 });
				}
			}
		}

		if (list.size() == 0) {
			bw.write("Oh no!");
		} else if (list.size() == 1) {
			bw.write(list.get(0)[0] + " " + list.get(0)[1]);
		} else {
			bw.write("Oh no! " + list.size() + " locations");
		}
		bw.flush();
	}
}
변수)
r, c : 행, 열
arr : 지도
dx, dy : 8방향
list : 보물의 위치 

 

행, 열을 입력받는다. 행, 열 크기만큼 지도 정보를 입력받아 arr에 저장한다. arr을 전체 탐색하며 0이라면 8방향을 살펴본다. 이때, 8방향 모두 O라면 ArrayList에 위치를 저장한다. 

 

최종 ArrayList의 크기가 0이면 'Oh no!'를 출력하고, 크기가 1이면 위치를, 크기가 2 이상이면 'Oh no! N locations'를 출력한다.



 

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

[Baekjoon] 6107_Plumbing the Pond  (0) 2026.04.23
[Baekjoon] 6754_Bridge transport  (0) 2026.04.22
[Baekjoon] 27137_Square Designs  (0) 2026.04.21
[Baekjoon] 13382_Lab  (0) 2026.04.20
[Baekjoon] 9354_It Is Cold  (0) 2026.04.10