|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Solution { |
| 6 | + static int N, maxCount; |
| 7 | + static int[][] map; |
| 8 | + static boolean[] dessertVisited; |
| 9 | + |
| 10 | + static int[] di = {1, 1, -1, -1}; |
| 11 | + static int[] dj = {1, -1, -1, 1}; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + //System.setIn(new FileInputStream("sample_input.txt")); |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + int T = Integer.parseInt(br.readLine()); |
| 17 | + StringTokenizer st; |
| 18 | + for (int t = 1; t <= T; t++) { |
| 19 | + N = Integer.parseInt(br.readLine()); |
| 20 | + map = new int[N][N]; |
| 21 | + for (int i = 0; i < N; i++) { |
| 22 | + st = new StringTokenizer(br.readLine()); |
| 23 | + for (int j = 0; j < N; j++) { |
| 24 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 25 | + } |
| 26 | + } |
| 27 | + maxCount = -1; |
| 28 | + |
| 29 | + for (int i = 0; i < N - 1; i++) { |
| 30 | + for (int j = 1; j < N - 1; j++) { |
| 31 | + dessertVisited = new boolean[101]; |
| 32 | + dessertVisited[map[i][j]] = true; |
| 33 | + dfs(i, j, i, j, 1, 0, 0); |
| 34 | + } |
| 35 | + } |
| 36 | + System.out.println("#" + t + " " + maxCount); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + static void dfs(int startI, int startJ, int curI, int curJ, int count, int d, int turn) { |
| 41 | + |
| 42 | + for (int newdirection = d; newdirection <= d + 1 && newdirection < 4; newdirection++) { |
| 43 | + int newi = curI + di[newdirection]; |
| 44 | + int newj = curJ + dj[newdirection]; |
| 45 | + |
| 46 | + if (newi < 0 || newi >= N || newj < 0 || newj >= N) |
| 47 | + continue; |
| 48 | + |
| 49 | + if (newi == startI && newj == startJ && count >= 4) { |
| 50 | + maxCount = Math.max(maxCount, count); |
| 51 | + continue; |
| 52 | + } |
| 53 | + if (dessertVisited[map[newi][newj]]) |
| 54 | + continue; |
| 55 | + |
| 56 | + dessertVisited[map[newi][newj]] = true; |
| 57 | + dfs(startI, startJ, newi, newj, count + 1, newdirection, (newdirection == d ? turn : turn + 1)); |
| 58 | + dessertVisited[map[newi][newj]] = false; |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +``` |
0 commit comments