BAEK_17780_새로운 게임
in Sidemenu / BaekJoon
17780. 새로운 게임
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Main {
static int N, K, r, c, dir, turn = 1;
static int[][] color, pos = { { 0, 0 }, { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 } };
static ArrayList<int[]>[][] chess;
static Map<Integer, int[]> map = new HashMap<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = toInt(st.nextToken());
K = toInt(st.nextToken());
color = new int[N][N];
chess = new ArrayList[N][N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
color[i][j] = toInt(st.nextToken());
chess[i][j] = new ArrayList<>();
}
}
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
r = toInt(st.nextToken()) - 1;
c = toInt(st.nextToken()) - 1;
dir = toInt(st.nextToken());
chess[r][c].add(new int[] { i, dir });
map.put(i, new int[] { r, c });
}
System.out.println(move());
}
static int move() {
while (turn <= 1000) {
for (int i = 0; i < K; i++) {
int[] location = map.get(i);
r = location[0];
c = location[1];
int[] bottom = chess[r][c].get(0);
if (bottom[0] == i) {
dir = bottom[1];
int nr = r + pos[dir][0];
int nc = c + pos[dir][1];
if (isBlue(nr, nc)) {
dir = newDir();
int revNr = r + pos[dir][0];
int revNc = c + pos[dir][1];
bottonToRev();
if (!isBlue(revNr, revNc)) {
if (isOverFour(revNr, revNc)) {
return turn;
}
whiteOrRed(color[revNr][revNc], revNr, revNc);
}
} else {
if (isOverFour(nr, nc)) {
return turn;
}
whiteOrRed(color[nr][nc], nr, nc);
}
}
}
turn++;
}
return -1;
}
static void bottonToRev() {
chess[r][c].add(0, new int[] { chess[r][c].get(0)[0], dir });
chess[r][c].remove(1);
}
static void whiteOrRed(int color, int nr, int nc) {
int size = chess[r][c].size();
for (int i = 0; i < size; i++) {
chess[nr][nc].add(chess[r][c].get(color == 0 ? i : size - 1 - i));
map.replace(chess[r][c].get(i)[0], new int[] { nr, nc });
}
chess[r][c] = new ArrayList<>();
}
static boolean isOverFour(int nr, int nc) {
return chess[r][c].size() + chess[nr][nc].size() >= 4 ? true : false;
}
static boolean isBlue(int r, int c) {
return (r < 0 || c < 0 || r >= N || c >= N || color[r][c] == 2) ? true : false;
}
static int newDir() {
return dir % 2 == 0 ? dir - 1 : dir + 1;
}
static int toInt(String input) {
return Integer.parseInt(input);
}
}