結果

問題 No.157 2つの空洞
ユーザー HAHAHAHAHAHA
提出日時 2016-08-24 14:55:45
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,243 bytes
コンパイル時間 1,341 ms
コンパイル使用メモリ 165,392 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-25 15:04:17
合計ジャッジ時間 2,229 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,816 KB
testcase_01 AC 1 ms
6,940 KB
testcase_02 AC 2 ms
6,940 KB
testcase_03 AC 1 ms
6,940 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 1 ms
6,944 KB
testcase_06 AC 1 ms
6,940 KB
testcase_07 AC 2 ms
6,940 KB
testcase_08 AC 2 ms
6,940 KB
testcase_09 AC 2 ms
6,940 KB
testcase_10 AC 1 ms
6,944 KB
testcase_11 AC 2 ms
6,940 KB
testcase_12 AC 2 ms
6,940 KB
testcase_13 AC 2 ms
6,940 KB
testcase_14 AC 1 ms
6,940 KB
testcase_15 AC 2 ms
6,940 KB
testcase_16 AC 2 ms
6,944 KB
testcase_17 AC 1 ms
6,944 KB
testcase_18 AC 2 ms
6,940 KB
testcase_19 AC 2 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;

int dy[]={0,  0, 1, -1};
int dx[]={1, -1, 0,  0};

int W,H;
string s[30];
int A[30][30];

void dfs(int y, int x, int n){
	if(y<0 || y>=H || x<0 || x>=W)
		return;
	if(s[y][x]=='#' || A[y][x]!=-1)
		return;
	
	A[y][x]=n;
	for(int i=0;i<4;i++)
	dfs(y+dy[i],x+dx[i],n);
}

int B[30][30];
int bfs(){
	memset(B,-1,sizeof(B));
	
	queue<pair<int, int> > Q;
	for(int y=0;y<H;y++){
		for(int x=0;x<W;x++){
			if(A[y][x]!=0)
				continue;
			
			B[y][x]=0;
			Q.push(make_pair(y,x));
		}
	}
	
	while(!Q.empty()){
		pair<int,int> ps=Q.front(); Q.pop();
		int y=ps.first;
		int x=ps.second;
		int z=B[y][x];
		
		for(int i=0;i<4;i++){
			int ny=y+dy[i];
			int nx=x+dx[i];
			
			if(ny<0 || ny>=H || nx<0 || nx>=W)
				continue;
			
			if(B[ny][nx]!=-1)
				continue;
			
			B[ny][nx]=z+1;
			Q.push(make_pair(ny,nx));
		}
	}
	
	int res=1<<25;
	for(int y=0;y<H;y++){
		for(int x=0;x<W;x++){
			if(A[y][x]==1)
			res=min(res,B[y][x]);
		}
	}
	
	return res-1;
}

int main(){
	memset(A,-1,sizeof(A));
	
	cin >> W >> H;
	for(int i=0;i<H;i++) cin >> s[i];
	
	int n=0;
	for(int y=0;y<H;y++){
		for(int x=0;x<W;x++){
			if(s[y][x]=='.' && A[y][x]==-1)
			dfs(y,x,n++);
		}
	}	
	
	cout << bfs() << endl;
	return 0;
}
0