結果
| 問題 |
No.228 ゆきこちゃんの 15 パズル
|
| コンテスト | |
| ユーザー |
tenten
|
| 提出日時 | 2023-07-27 14:21:37 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 78 ms / 5,000 ms |
| コード長 | 3,868 bytes |
| コンパイル時間 | 2,309 ms |
| コンパイル使用メモリ | 83,876 KB |
| 実行使用メモリ | 51,920 KB |
| 最終ジャッジ日時 | 2024-10-04 10:05:40 |
| 合計ジャッジ時間 | 4,444 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 17 |
ソースコード
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main {
static int[][] goal = new int[4][4];
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
int[][] org = new int[4][4];
int idx = 1;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
goal[i][j] = sc.nextInt();
org[i][j] = idx % 16;
idx++;
}
}
check(org, new boolean[16]);
System.out.println("No");
}
static boolean same(int[][] org) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (goal[i][j] != org[i][j]) {
return false;
}
}
}
return true;
}
static void check(int[][] org, boolean[] used) {
if (same(org)) {
System.out.println("Yes");
System.exit(0);
}
int r = 0;
int c = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (org[i][j] == 0) {
r = i;
c = j;
break;
}
}
}
if (r > 0) {
int v = org[r - 1][c];
if (!used[v]) {
org[r - 1][c] = 0;
org[r][c] = v;
used[v] = true;
check(org, used);
used[v] = false;
org[r - 1][c] = v;
org[r][c] = 0;
}
}
if (r < 3) {
int v = org[r + 1][c];
if (!used[v]) {
org[r + 1][c] = 0;
org[r][c] = v;
used[v] = true;
check(org, used);
used[v] = false;
org[r + 1][c] = v;
org[r][c] = 0;
}
}
if (c > 0) {
int v = org[r][c - 1];
if (!used[v]) {
org[r][c - 1] = 0;
org[r][c] = v;
used[v] = true;
check(org, used);
used[v] = false;
org[r][c - 1] = v;
org[r][c] = 0;
}
}
if (c < 3) {
int v = org[r][c + 1];
if (!used[v]) {
org[r][c + 1] = 0;
org[r][c] = v;
used[v] = true;
check(org, used);
used[v] = false;
org[r][c + 1] = v;
org[r][c] = 0;
}
}
}
}
class Utilities {
static String arrayToLineString(Object[] arr) {
return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n"));
}
static String arrayToLineString(int[] arr) {
return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new));
}
}
class Scanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
StringBuilder sb = new StringBuilder();
public Scanner() throws Exception {
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public int[] nextIntArray() throws Exception {
return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
public String next() throws Exception {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
tenten