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

*/

Related Posts:

  • Y7M2 P2A 練習-1大數相加    ✔ 大數相乘    ✔ n階乘           ✔ 大數相加================ 最多 1000位的兩個非負整數相加 #include &… Read More
  • APCS 105年3月題4-血緣關係(C++參考)APCS Y16M3-Q3 - 血緣關係 /* apcs-4 : 105年3月5日 APCS 試題 Q4 - 血緣關係  , 原題應不需多測資,本參考解為多測資 EOF   找每一葉節點的(最長距len、最大子樹高h1、次大子樹高h2),求max(len, h1+h2)… Read More
  • APCS 105年3月題3-線段覆蓋長度(C++參考)APCS Y16M3-Q3 - 線段覆蓋長度  問題描述 #include <iostream> #include <cmath> #include <algorithm> using namespace std; const int Max… Read More
  • Y7M2 P2A 練習-2100北二區資訊複賽 1.圈叉連線數問題(zj:a817) 2.藏寶問題(zj:a824)                ✔ 3.小四數學(zj:a825) 4.天氣預測問題(zj:a826)… Read More
  • 09/24排列組合9月24日 研討之排列組合相關檔案( 可列表及下載 )… Read More

0 意見:

張貼留言