結果

問題 No.13 囲みたい!
ユーザー uafr_csuafr_cs
提出日時 2017-10-30 17:31:47
言語 Java21
(openjdk 21)
結果
AC  
実行時間 253 ms / 5,000 ms
コード長 1,908 bytes
コンパイル時間 2,392 ms
コンパイル使用メモリ 78,344 KB
実行使用メモリ 46,288 KB
最終ジャッジ日時 2023-08-14 13:13:31
合計ジャッジ時間 6,185 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 120 ms
39,684 KB
testcase_01 AC 117 ms
39,220 KB
testcase_02 AC 117 ms
39,556 KB
testcase_03 AC 246 ms
46,156 KB
testcase_04 AC 229 ms
45,560 KB
testcase_05 AC 249 ms
46,288 KB
testcase_06 AC 229 ms
44,224 KB
testcase_07 AC 231 ms
44,120 KB
testcase_08 AC 253 ms
45,788 KB
testcase_09 AC 250 ms
45,760 KB
testcase_10 AC 186 ms
41,672 KB
testcase_11 AC 238 ms
44,668 KB
testcase_12 AC 194 ms
41,044 KB
testcase_13 AC 208 ms
43,088 KB
testcase_14 AC 206 ms
43,056 KB
testcase_15 AC 127 ms
39,720 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
	
	public static final int UNVISITED = 0;
	public static final int VISITING = 1;
	public static final int VISITED = 2;
	
	public static final int[][] move_dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
	public static boolean in_range(int x, int y, int W, int H){
		return 0 <= x && x < W && 0 <= y && y < H;
	}
	
	public static boolean dfs(int x, int y, int px, int py, int H, int W, int[][] board, int[][] visited){
		//System.out.println(y + " " + x + " " + board[y][x]);
		visited[y][x] = VISITING;
		
		for(final int[] move : move_dirs){
			final int nx = x + move[0];
			final int ny = y + move[1];
			
			if(!in_range(nx, ny, W, H)){ continue; }
			if(board[y][x] != board[ny][nx]){ continue; }
			if(ny == py && nx == px){ continue; }
			
			if(visited[ny][nx] == UNVISITED){
				if(dfs(nx, ny, x, y, H, W, board, visited)){
					visited[y][x] = VISITED;
					return true;
				}
			}else if(visited[ny][nx] == VISITING){
				visited[y][x] = VISITED;
				return true;
			}
		}
		
		visited[y][x] = VISITED;
		return false;
	}
	
	public static void main(final String[] args){
		new Thread(null, new Runnable(){
			@Override
			public void run() {
				_main(args);
			}
		}, "", 100 * 1024 * 1024).start();
	}
	
	public static void _main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		final int W = sc.nextInt();
		final int H = sc.nextInt();
		
		int[][] board = new int[H][W];
		for(int i = 0; i < H; i++){
			for(int j = 0; j < W; j++){
				board[i][j] = sc.nextInt();
			}
		}
		
		int[][] visited = new int[H][W];
		
		for(int y = 0; y < H; y++){
			for(int x = 0; x < W; x++){
				if(visited[y][x] != UNVISITED){ continue; }
				
				if(dfs(x, y, -1, -1, H, W, board, visited)){
					System.out.println("possible");
					return;
				}
			}
		}
		
		System.out.println("impossible");
	}
}
0