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
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Solution {
static int N;
static int[][] board;
static int res;
// ↘ ↙ ↖ ↗
static int[] dr = { 1, 1, -1, -1 };
static int[] dc = { 1,-1, -1, 1 };
static boolean[][] visited;
static HashSet<Integer> set = new HashSet<>();
static void go(int sr, int sc, int r, int c, int dir, int dir0Cnt, int dir1Cnt) {
if (visited[r][c]) {
if (sr == r && sc == c)
res = Math.max(res, set.size());
return;
}
if (set.contains(board[r][c])) return;
set.add(board[r][c]);
visited[r][c] = true;
for (int ndir = dir; ndir < dir + 2; ndir++) {
int nr = r + dr[ndir % 4];
int nc = c + dc[ndir % 4];
if \(nr < 0 \|| nr >= N \|| nc < 0 \|| nc >= N) continue;
int nDir0Cnt = dir0Cnt;
int nDir1Cnt = dir1Cnt;
if (ndir == 0) nDir0Cnt++;
else if (ndir == 1) nDir1Cnt++;
else if (ndir == 2) nDir0Cnt--;
else nDir1Cnt--;
if \(nDir0Cnt < 0 \|| nDir1Cnt < 0) continue;
go(sr, sc, nr, nc, ndir, nDir0Cnt, nDir1Cnt);
}
set.remove(board[r][c]);
visited[r][c] = false;
}
static void solution() {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
go(i, j, i, j, 0, 0, 0);
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(in.readLine());
for (int tc = 1; tc <= testcase; tc++) {
res = -1;
N = Integer.parseInt(in.readLine());
board = new int[N][N];
visited = new boolean[N][N];
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(in.readLine(), " ");
for (int j = 0; j < N; j++)
board[i][j] = Integer.parseInt(st.nextToken());
}
solution();
System.out.println("#" + tc + " " + res);
}
}
}
|