2016年7月20日 星期三

dfs-1 (C++參考)

/*
dfs-1 A,B 水窪數及最大窪值
*/

#include <iostream>
using namespace std;

const int MaxN = 100;
int a[MaxN][MaxN] , m, n;
int dr[]={-1,1,0,0};  //列位移值: 上下左右
int dc[]={0,0,-1,1};  //行位移值: 上下左右


void dfs(int i, int j , int& cnt)
{
int stki[MaxN*MaxN] , stkj[MaxN*MaxN] , p=0;
stki[p]=i; stkj[p]=j;  p++;  // push (i,j) to stack
cnt = 1;  a[i][j] = 0;
while( p>0 )  // stack not empty
{
p-- ;  i = stki[p];  j = stkj[p];  // pop(i,j) form stack
for(int d=0; d<4; ++d)
{
int ni=i+dr[d] , nj=j+dc[d];  //上下左右的座標(ni,nj)
if( ni<0 || ni>=m || nj<0 || nj>=n ) continue;  // 超出範圍
if( a[ni][nj] == 1 ) // 有連通 將(ni,nj) push
{
stki[p]=ni; stkj[p]=nj;  p++;  // push (i,j) to stack
cnt++ ;  a[ni][nj] = 0;
}
}
}
}

int main(void)
{
int t,i,j,k ;
string s;
cin >> t; // t 組
while(t--)
{
cin >> m >> n;
for(i=0; i<m; ++i)
{
cin >> s;   // read one line
for(j=0; j<n; ++j)
a[i][j] = (s[j]=='1'); // if'1' set a[i][j]=true 即 =1
}
int ans=0 , mx = 0 , cnt;
for(i=0; i<m; ++i)
{
for(j=0; j<n; ++j)
{
if( a[i][j] )  // 有窪,
{
ans++;  // 計次
dfs(i,j,cnt);  // cnt 傳參考,可傳回此處的窪值
if(cnt>mx) mx=cnt;  //保留最大的 窪值
}
}
}
cout << ans <<',' << mx << endl;
}
return 0;
}
/*
輸入
5
7 7
0000111
0110101
0010101
1010000
1010011
0000001
0111100
7 7
1000111
0110101
0010010
1100000
0011011
1000001
0111100
1 8
110000010
5 5
00001
01101
01001
11101
11001
3 5
01001
00110
01001

*/

0 意見:

張貼留言