-
Notifications
You must be signed in to change notification settings - Fork 3
/
flipfive.java
82 lines (81 loc) · 2.4 KB
/
flipfive.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Daniel West
import java.util.Scanner;
import java.util.TreeMap;
public class flipfive {
static boolean[][] curr, used;
static TreeMap<grid, Integer> moves;
static int currMoves;
public static void main (String[] args){
curr = new boolean[3][3];
used = new boolean[3][3];
moves = new TreeMap<grid, Integer>();
currMoves = 0;
dfs();
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
sc.nextLine();
for(int i = 0; i < c; i++){
boolean[][] in = new boolean[3][3];
for(int R = 0; R < 3; R++){
String line = sc.nextLine();
for(int C = 0; C < 3; C++){
if(line.charAt(C) == '*'){
in[R][C] = true;
}
}
}
grid currGrid = new grid(in);
int out = moves.get(currGrid);
System.out.println(out);
}
}
static void opp(int rIn, int cIn){
if(rIn < 0 || rIn >= 3 || cIn < 0 || cIn >= 3) return;
curr[rIn][cIn] = !curr[rIn][cIn];
}
static void flip(int rIn, int cIn){
opp(rIn - 1, cIn);
opp(rIn + 1, cIn);
opp(rIn, cIn - 1);
opp(rIn, cIn + 1);
opp(rIn, cIn);
}
static void dfs(){
grid temp = new grid(curr);
if(!moves.containsKey(temp)) moves.put(temp, currMoves);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(used[i][j]) continue;
flip(i, j);
used[i][j] = true;
currMoves++;
dfs();
flip(i, j);
used[i][j] = false;
currMoves--;
}
}
}
}
class grid implements Comparable<grid> {
boolean[][] arr;
int index;
grid(boolean[][] arrIn){
arr = new boolean[3][3];
index = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(arrIn[i][j]){
arr[i][j] = true;
int temp = (3 * i) + j;
index += Math.pow(2, temp);
}
}
}
}
public int compareTo(grid in){
if(index < in.index) return -1;
if(index > in.index) return 1;
return 0;
}
}