package xj;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class PlaneYang {
static int N, max,sum;
static int data[][];
static int x, y;
static boolean boom;
public static void main(String[] args) throws FileNotFoundException {
/* Scanner sc=new Scanner(System.in); */
Scanner sc = new Scanner(new File(“src/Plane”));
while (sc.hasNext()) {
N = sc.nextInt();
data = new int[N][5];
boom = true;
for (int i = 0; i < N; i++) {
for (int j = 0; j < 5; j++) {
data[i][j] = sc.nextInt();
}
}
x = N;
y = 2;
max=-1;
sum=0;
dfs(0);
if(max==-1){
System.out.println(“-1”);
}
else{System.out.println(max);}
}
sc.close();
}
private static void dfs(int step) {
if (step == N||sum<0) {
if (max < sum) {
max = sum;
}
return;
}
if (sum + (N – step) <= max) {
return;
}
// zuo
if (x – 1 >= 0 && y – 1 >= 0) {
if((data[x – 1][y – 1] == 2 && sum >= 0)||data[x-1][y-1]!=2){
if (data[x – 1][y – 1] == 1) {
sum++;
}
if (data[x – 1][y – 1] == 2) {
sum–;
}
x -= 1;
y -= 1;
dfs(step + 1);
x += 1;
y += 1;
if (data[x – 1][y – 1] == 1) {
sum–;
}
if (data[x – 1][y – 1] == 2 ) {
sum++;
}
}
}
// you
if (x – 1 >= 0 &&y+1<5) {
if((data[x-1][y+1] == 2 && sum >= 0)||data[x-1][y+1]!=2){
if (data[x-1][y+1] == 1) {
sum++;
}
if (data[x-1][y+1] == 2) {
sum–;
}
x -= 1;
y += 1;
dfs(step+1);
x += 1;
y -= 1;
if (data[x – 1][y+1] == 1){
sum–;
}
if (data[x – 1][y+1] == 2 ){
sum++;
}
}
}
// bu dong
if (x – 1 >= 0) {
if((data[x-1][y] == 2 && sum>= 0)||data[x-1][y]!=2){
if (data[x-1][y] == 1) {
sum++;
}
if (data[x-1][y] == 2) {
sum–;
}
x -= 1;
dfs(step+1);
x += 1;
if (data[x – 1][y] == 1){
sum–;
}
if (data[x – 1][y] == 2 ){
sum++;
}
}
}
//
if (boom) {
boom = false;
int k = x;
int n = 0;
while (k – 1 >= 0) {
k–;
n++;
for (int j = 0; j < 5; j++) {
if (data[k][j] == 2) {
data[k][j] = 4;
}
}
if (n == 5) {
break;
}
}
dfs(step);
k=x;
n=0;
while (k – 1 >= 0) {
k–;
n++;
for (int j = 0; j < 5; j++) {
if (data[k][j] == 4) {
data[k][j] = 2;
}
}
if (n == 5) {
break;
}
}
boom = true;
}
}
}
//input
8
0 1 0 1 2
1 1 0 1 0
2 2 1 0 1
1 2 0 2 1
0 1 0 1 2
1 1 0 1 0
2 2 1 0 1
1 2 0 2 1
7
1 2 0 0 1
2 0 0 1 0
0 1 2 0 1
1 0 0 2 1
0 2 1 0 1
0 1 2 2 2
1 0 1 1 0
12
1 2 1 0 1
2 0 1 0 1
2 2 2 2 1
1 1 1 1 0
0 0 0 1 0
0 1 0 2 1
1 2 1 2 0
1 1 1 2 2
2 0 0 1 0
1 0 1 0 0
0 1 0 2 2
0 0 1 2 1
12
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
12
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
12
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
6
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
1 1 1 1 1
2 2 2 2 2
7
2 2 2 2 2
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 1 1 1 1
0 2 2 2 0
7
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
1 1 1 1 1
2 2 2 2 2
//output
7
6
11
0
12
-1
0
0
-1