728x90
문제
접근 방식
그래프 문제도 아니고 그냥 일반적인 반복문 문제라
입력 받고 8방향 중 한 방향으로 4개의 알파벳들이 각각 O B I S인지 모두 확인해주면 된다.
문자 배열을 미리 만들어두고 비교를 했는데 목표 단어에 중복된 문자가 존재하지 않아서
애초에 M을 1, O를 2, ..., S를 5로 두고 증가하는 순으로 비교하면 더 깔끔할거 같다.
풀이
public class Main {
static int n, cnt = 0;
static char[] chars = new char[]{'O', 'B', 'I', 'S'};
static char[][] map;
static int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
static int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
map = new char[n][n];
Queue<Pair> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
String str = br.readLine();
for (int j = 0; j < n; j++) {
char c = str.charAt(j);
map[i][j] = c;
if (c == 'M') q.offer(new Pair(i, j));
}
}
while (!q.isEmpty()) {
Pair cur = q.poll();
for (int dir = 0; dir < 8; dir++) {
int nx = cur.x + dx[dir] * 4;
int ny = cur.y + dy[dir] * 4;
if (nx < 0 || ny < 0 || nx >= n || ny >= n) continue;
int x = cur.x + dx[dir];
int y = cur.y + dy[dir];
for (int i = 0; i < 4; i++) {
if (map[x][y] != chars[i]) break;
x += dx[dir];
y += dy[dir];
if (i == 3) cnt++;
}
}
}
System.out.println(cnt);
}
static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
}
'Java > Algorithms' 카테고리의 다른 글
[백준] 12888번 : 포화 이진 트리 도로 네트워크 (0) | 2024.07.14 |
---|---|
[백준] 1976번 : 여행 가자 (0) | 2024.06.03 |
[백준] 20208번 : 진우의 민트초코우유 (0) | 2024.05.05 |
[백준] 16928번 : 뱀과 사다리 게임 (0) | 2024.04.21 |
[백준] 11054번 : 가장 긴 바이토닉 부분 수열 (1) | 2024.04.20 |