SWEA 1861正方形部屋



BFSまたはDFSを使用して、条件に従って2 D配列を参照できます.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Solution {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;
	static int[][] map;
	static boolean[] possible; // 각 인덱스 숫자가 다음 숫자와 이어지면 ture.

	static int N;

	static void exmMap() { // 사방 검사 후 i + 1값이 주위에 있는 지 검사하여 possible에 넣음.
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				int tmp = map[i][j];
				if (i + 1 < N && tmp + 1 == map[i + 1][j]) {
					possible[tmp - 1] = true;
				} else if (i - 1 >= 0 && tmp + 1 == map[i - 1][j]) {
					possible[tmp - 1] = true;
				} else if (j - 1 >= 0 && tmp + 1 == map[i][j - 1]) {
					possible[tmp - 1] = true;
				} else if (j + 1 < N && tmp + 1 == map[i][j + 1]) {
					possible[tmp - 1] = true;
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));
		int T = Integer.parseInt(br.readLine());
		for (int tc = 1; tc <= T; tc++) {
			N = Integer.parseInt(br.readLine());
			map = new int[N][N];
			possible = new boolean[N * N];
			for (int i = 0; i < N; i++) {
				st = new StringTokenizer(br.readLine(), " ");
				for (int j = 0; j < N; j++) {
					map[i][j] = Integer.parseInt(st.nextToken());
				}
			}

			exmMap();
			
			int max_count = 1, count = 1, numofMax = 1, idx = 0;
			while(true) {
				if(idx >= N * N) break;
				if(possible[idx]) {
					count++;
					if(max_count < count) {
						max_count = count;
						numofMax = idx + 3 - count;
					}
				}else {
					count = 1;
				}
				idx++;				
			}
			
			bw.append(String.format("#%d %d %d\n", tc, numofMax, max_count));

		}
		bw.flush();
		bw.close();
	}
}