-
[Java] BOJ 1986 체스개발자 취업/코딩테스트 준비 2023. 4. 27. 22:20반응형
1986번: 체스
첫째 줄에는 체스 판의 크기 n과 m이 주어진다. (1 ≤ n, m ≤ 1000) 그리고 둘째 줄에는 Queen의 개수와 그 개수만큼의 Queen의 위치가 입력된다. 그리고 마찬가지로 셋째 줄에는 Knight의 개수와 위치,
www.acmicpc.net
정답 코드
- 퀸 / 나이트 / 폰의 위치를 2차원 배열에 저장하기
- 퀸 / 나이트의 방문 가능한 위치 확인
- 퀸 8방향 직선이동 (장애물 만날시 멈춤)
- 나이트 8방향 대각선 이동 (장애물 있어도 건너뜀)
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static BufferedWriter bw; static StringTokenizer st; static int N, M; static char[][] arr; static boolean[][] visit; static int[] qx = { 0, 1, 1, 1, 0, -1, -1, -1 }; static int[] qy = { -1, -1, 0, 1, 1, 1, 0, -1 }; static int[] kx = { 1, 2, 2, 1, -1, -2, -2, -1 }; static int[] ky = { -2, -1, 1, 2, 2, 1, -1, -2 }; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); st = new StringTokenizer(br.readLine(), " "); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); arr = new char[N][M]; visit = new boolean[N][M]; for (int tc = 0; tc < 3; tc++) { st = new StringTokenizer(br.readLine(), " "); char horse; if (tc == 0) { horse = 'Q'; } else if (tc == 1) { horse = 'K'; } else { horse = 'P'; } int cnt = Integer.parseInt(st.nextToken()); for (int i = 0; i < cnt; i++) { int r = Integer.parseInt(st.nextToken()) - 1; int c = Integer.parseInt(st.nextToken()) - 1; arr[r][c] = horse; visit[r][c] = true; } } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (arr[i][j] == 'Q') { moveQ(i, j); } else if (arr[i][j] == 'K') { moveK(i, j); } } } System.out.println(cnt()); } private static void moveK(int y, int x) { for (int dic = 0; dic < 8; dic++) { int nx = x + kx[dic]; int ny = y + ky[dic]; if (nx < 0 || ny < 0 || nx >= M || ny >= N) { continue; } visit[ny][nx] = true; } } private static void moveQ(int y, int x) { for (int dic = 0; dic < 8; dic++) { int nx = x + qx[dic]; int ny = y + qy[dic]; while (true) { if (nx < 0 || ny < 0 || nx >= M || ny >= N) { break; } if (Character.isAlphabetic(arr[ny][nx])) { break; } visit[ny][nx] = true; nx += qx[dic]; ny += qy[dic]; } } } private static int cnt() { int sum = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (!visit[i][j]) { sum++; } } } return sum; } }
'개발자 취업 > 코딩테스트 준비' 카테고리의 다른 글
[Java] BOJ 14888 연산자 끼워넣기 (0) 2023.05.01 [Java] BOJ 2217 로프 (0) 2023.04.28 [Java] BOJ 1522 문자열 교환 (0) 2023.04.26 [Java] BOJ 1406 에디터 (0) 2023.04.25 [Java] BOJ 14426 접두사 찾기 (1) 2023.04.25