Development Palette
b1331_나이트투어 본문
1331번: 나이트 투어
나이트 투어는 체스판에서 나이트가 모든 칸을 정확히 한 번씩 방문하며, 마지막으로 방문하는 칸에서 시작점으로 돌아올 수 있는 경로이다. 다음 그림은 나이트 투어의 한 예이다. 영식이는 6×
www.acmicpc.net
1. 이전좌표와 현재좌표의 길이의 차이로 판단하여 nightTour 하는 방법
package com.구현.b1331_나이트투어;
import java.util.Scanner;
public class Main2 {
static int[][] map = new int[6][6];
static int beforeR = 0;
static int beforeC = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
map = new int[6][6];
//System.out.println('B'-64);
int startR = 0;
int startC = 0;
for (int n = 0; n < 36; n++) {
String str = sc.next();
int r = str.charAt(0) - 'A';
int c = str.charAt(1) - '0' - 1;
//System.out.println(r+" "+c);
if (n == 0) {
startR = r;
startC = c;
beforeR = r;
beforeC = c;
continue;
}
if (!nightTour(r, c)) result(false);
}
// 마지막이 시작점으로 갈수있는지
if (!nightTour(startR, startC)) result(false);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (map[i][j] != 1) result(false);
}
}
result(true);
sc.close();
}
private static void result(boolean b) {
System.out.println(b ? "Valid" : "Invalid");
System.exit(0);
}
private static boolean nightTour(int r, int c) {
int rowL = Math.abs(r-beforeR);
int columnL = Math.abs(c-beforeC);
if((rowL==1&&columnL==2)||(rowL==2&&columnL==1)) {
map[r][c]++;
beforeR = r;
beforeC = c;
return true;
}
return false;
}
}
2. nightTour를 8방 탐색으로 하는 방법
package com.구현.b1331_나이트투어;
import java.util.Scanner;
public class Main {
static int[][] map = new int[6][6];
//우하 우상 하우 하좌 좌하 좌상 상우 상좌
static int[] dr = {2, -2, 1, 1, 2, -2, -1, -1};
static int[] dc = {1, 1, 2, -2, -1, -1, 2, -2};
static int beforeR = 0;
static int beforeC = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
map = new int[6][6];
//System.out.println('B'-64);
int startR = 0;
int startC = 0;
for (int n = 0; n < 36; n++) {
String str = sc.next();
int r = str.charAt(0) - 'A';
int c = str.charAt(1) - '0' - 1;
//System.out.println(r+" "+c);
if (n == 0) {
startR = r;
startC = c;
beforeR = r;
beforeC = c;
continue;
}
if (!nightTour(r, c)) result(false);
}
// 마지막이 시작점으로 갈수있는지
if (!nightTour(startR, startC)) result(false);
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (map[i][j] != 1) result(false);
}
}
result(true);
sc.close();
}
private static void result(boolean b) {
System.out.println(b ? "Valid" : "Invalid");
System.exit(0);
}
private static boolean nightTour(int r, int c) {
for (int d = 0; d < 8; d++) {
int nr = beforeR + dr[d];
int nc = beforeC + dc[d];
if (nr < 0 || nc < 0 || nr >= 6 || nc >= 6) continue;
if (nr == r && nc == c) {
map[nr][nc]++;
beforeR = nr;
beforeC = nc;
return true;
//System.out.println(nr+","+nc);
}
}
return false;
}
}
'Algorithm > Baekjoon' 카테고리의 다른 글
b2206_벽부수고이동하기; (0) | 2021.10.08 |
---|---|
b11401_이항계수3 (0) | 2021.10.04 |
[파스칼의 삼각형] b11050_이항계수1 (0) | 2021.10.04 |
b17144_미세먼지안녕 (0) | 2021.09.24 |
[KMP알고리즘]b1786_찾기 (0) | 2021.09.24 |
Comments