結果
| 問題 |
No.157 2つの空洞
|
| コンテスト | |
| ユーザー |
jp_ste
|
| 提出日時 | 2015-03-17 11:19:06 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 150 ms / 2,000 ms |
| コード長 | 2,769 bytes |
| コンパイル時間 | 2,407 ms |
| コンパイル使用メモリ | 78,520 KB |
| 実行使用メモリ | 45,276 KB |
| 最終ジャッジ日時 | 2024-06-28 23:07:21 |
| 合計ジャッジ時間 | 5,979 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 16 |
ソースコード
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int W, H;
static char C[][];
static int DP[][];
static int mAns = Integer.MAX_VALUE;
public static void main(String[] args) {
readMap();
boolean find = false;
for(int i=0; i<H; i++) {
for(int j=0; j<W; j++) {
if(C[i][j] == '.') {
replaceCavity(j, i, '+');
find=true;
break;
}
}
if(find) break;
}
for(int i=0; i<H; i++) {
for(int j=0; j<W; j++) {
if(C[i][j] == '.') {
solve(j, i);
}
}
}
System.out.println(mAns-1);
}
static void solve(int startX, int startY) {
Queue<Node> q = new LinkedList<Node>();
Node start = new Node(startX, startY, 0, C);
q.add(start);
while(!q.isEmpty()) {
Node node = q.poll();
if(DP[node.mY][node.mX] <= node.mStep) continue;
DP[node.mY][node.mX] = node.mStep;
if(mAns <= node.mStep) continue;
if(node.mX == 0 || node.mX == W-1) continue;
if(node.mY == 0 || node.mY == H-1) continue;
if(node.mMap[node.mY][node.mX] == '+') {
mAns = Math.min(mAns, node.mStep);
continue;
}
node.mMap[node.mY][node.mX] = '.';
int nextStep = node.mStep+1;
int nextX, nextY;
char nextMap[][] = node.mMap;
//上
nextX = node.mX;
nextY = node.mY-1;
if(node.mMap[nextY][nextX] != '.') {
Node next = new Node(nextX, nextY, nextStep, nextMap);
q.add(next);
}
//右
nextX = node.mX+1;
nextY = node.mY;
if(node.mMap[nextY][nextX] != '.') {
Node next = new Node(nextX, nextY, nextStep, nextMap);
q.add(next);
}
//下
nextX = node.mX;
nextY = node.mY+1;
if(node.mMap[nextY][nextX] != '.') {
Node next = new Node(nextX, nextY, nextStep, nextMap);
q.add(next);
}
//左
nextX = node.mX-1;
nextY = node.mY;
if(node.mMap[nextY][nextX] != '.') {
Node next = new Node(nextX, nextY, nextStep, nextMap);
q.add(next);
}
}
}
static void readMap() {
Scanner sc = new Scanner(System.in);
W = sc.nextInt();
H = sc.nextInt();
C = new char[H][W];
DP = new int[H][W];
for(int i=0; i<H; i++) {
String line = sc.next();
for(int j=0; j<W; j++) {
C[i][j] = line.charAt(j);
DP[i][j] = Integer.MAX_VALUE;
}
}
}
static void replaceCavity(int j, int i, char v) {
if(C[i][j] != '.') return;
C[i][j] = v;
replaceCavity(j+1, i , v);
replaceCavity(j , i+1, v);
replaceCavity(j-1, i , v);
replaceCavity(j , i-1, v);
}
}
class Node {
int mX, mY, mStep;
char mMap[][];
Node(int x, int y, int step, char[][] map) {
mX = x; mY = y; mStep = step;
mMap = new char[Main.H][Main.W];
for(int i=0; i<Main.H; i++) {
mMap[i] = map[i].clone();
}
}
}
jp_ste