結果

問題 No.157 2つの空洞
ユーザー nCk_cv
提出日時 2016-02-18 11:07:42
言語 Java
(openjdk 23)
結果
AC  
実行時間 142 ms / 2,000 ms
コード長 1,972 bytes
コンパイル時間 2,249 ms
コンパイル使用メモリ 78,444 KB
実行使用メモリ 54,388 KB
最終ジャッジ日時 2024-09-22 11:55:32
合計ジャッジ時間 5,779 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;
import java.awt.geom.*;
import java.io.*;
public class Main {
	static int[] vx = {1,0,-1,0};
	static int[] vy = {0,1,0,-1};
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int w = sc.nextInt();
		int h = sc.nextInt();
		char[][] map = new char[h][];
		for(int i = 0; i < h; i++) {
			map[i] = sc.next().toCharArray();
		}
		int[][] sMap = new int[h][w];
		for(int i = 0; i < h; i++) {
			for(int j = 0; j < w; j++) {
				sMap[i][j] = 2 << 27;
			}
		}
		IN:for(int i = 0; i < h; i++) {
			for(int j = 0; j < w; j++) {
				if(map[i][j] == '.') {
					dfsA(i,j,0,sMap,map);
					break IN;
				}
			}
		}
		
		for(int i = 0; i < h; i++) {
			for(int j = 0; j < w; j++) {
				if(map[i][j] == '#' || sMap[i][j] != 0) continue;
				bfs(i,j,sMap,map);
			}
		}
		int MIN = 2 << 27;
		for(int i = 0; i < h; i++) {
			for(int j = 0; j < w; j++) {
				if(map[i][j] == '.' && sMap[i][j] != 0) MIN = Math.min(MIN, sMap[i][j]);
			}
		}
		System.out.println(MIN);
 	}
	static void bfs(int y, int x, int[][] sMap, char[][] map) {
		ArrayDeque<Data> queue = new ArrayDeque<Data>();
		queue.add(new Data(y,x,0));
		sMap[y][x] = 0;
		while(!queue.isEmpty()) {
			Data tmp = queue.pollFirst();
			for(int i = 0; i < 4; i++) {
				int tx = vx[i] + tmp.x;
				int ty = vy[i] + tmp.y;
				if(tx < 0 || ty < 0 || ty >= map.length || tx >= map[ty].length) continue;
				if(sMap[ty][tx] <= tmp.count) continue;
				sMap[ty][tx] = tmp.count;
				queue.add(new Data(ty,tx,tmp.count+1));
			}
		}
	}
	static class Data {
		int y;
		int x;
		int count;
		Data(int a, int b,int c) {
			 y = a;
			 x = b;
			 count = c;
		}
	}
	static void dfsA(int y,int x, int f, int[][] sMap, char[][] map) {
		sMap[y][x] = f;
		for(int i = 0; i < 4; i++) {
			int tx = vx[i] + x;
			int ty = vy[i] + y;
			if(tx < 0 || ty < 0 || ty >= map.length || tx >= map[ty].length || map[ty][tx] == '#' || sMap[ty][tx] == 0) continue;
			dfsA(ty,tx,f,sMap,map);
		}
	}
}
0