-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathB.java
79 lines (70 loc) · 2.33 KB
/
B.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
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
/**
* KickStart 2017 Round C
* Problem B. X Squared
*/
public class Main {
public String solve(Scanner scanner) {
int n=scanner.nextInt();
char[][] map=new char[n][n];
for (int i=0;i<n;i++) map[i]=scanner.next().toCharArray();
return check1(n, map)&&check2(n, map)?"POSSIBLE":"IMPOSSIBLE";
}
private boolean check1(int n, char[][] map) {
for (int i=0;i<n;i++) {
int u=0,v=0;
for (int j=0;j<n;j++) {
if (map[i][j]=='X') u++;
if (map[j][i]=='X') v++;
if (u>2 || v>2) return false;
}
}
return true;
}
private boolean check2(int n, char[][] map) {
boolean[] visited=new boolean[n];
ArrayList<Integer>[] lists=new ArrayList[n];
for (int i=0;i<n;i++) {
ArrayList<Integer> list=new ArrayList<>();
for (int j=0;j<n;j++) {
if (map[i][j]=='X') list.add(j);
}
if (list.size()>=3 || list.isEmpty()) return false;
lists[i]=list;
}
for (int i=0;i<n;i++) {
if (visited[i] || lists[i].size()==1) continue;
visited[i]=true;
boolean has=false;
for (int j=0;j<n;j++) {
if (!visited[j] && lists[j].equals(lists[i])) {
visited[j]=true;
has=true;
break;
}
}
if (!has) return false;
}
return true;
}
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream("output.txt"));
Scanner scanner=new Scanner(System.in);
int times=Integer.parseInt(scanner.nextLine());
long start=System.currentTimeMillis();
for (int t=1;t<=times;t++) {
try {
System.out.println(String.format("Case #%d: %s", t, new Main().solve(scanner)));
}
catch (Throwable e) {
System.err.println("ERROR in case #"+t);
e.printStackTrace();
}
}
long end=System.currentTimeMillis();
System.err.println(String.format("Time used: %.3fs", (end-start)/1000.0));
}
}