poj 1562 || zoj 1709 Oil Deposits(DFS)

來源:互聯網
上載者:User

題意:

油田問題:相鄰的可以合為一塊田,這裡相鄰是指邊上的8個方向…求最少油田數量。

分析:

本題實際上是做一個搜尋矩陣的連通子集。

簡單的dfs就可以解決,還不用剪枝。^_^

一開始我回溯考慮太多了,其實只需在dfs函數裡放個:

   if(a[x][y]=='*')return;就行的,

然後又有個問題:什麼時候計數增1.找我那麼做,要瘋了的。

現在只需在一開始從起點開始計算count++,搞定。

還有一個學習的就是對二位字串數組的初始化。

memset(a, '*', 105 * 105 * sizeof(char));

#include <stdio.h>#include <string.h>char a[105][105];int dir[8][2]={{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};int count,n,m,flag;void dfs(int x, int y){int i;if(a[x][y]=='*') return;a[x][y]='*';for(i=0;i<8;i++){dfs(x+dir[i][0],y+dir[i][1]);}}int main(){char s[1000];int i,j;while(scanf("%d%d",&n,&m)!=EOF){count=0;flag=0;memset(a, '*', 105 * 105 * sizeof(char));//對二維字串數組進行初始化if(n==0&&m==0) break;for(i=1;i<=n;i++){gets(s);for(j=1;j<=m;j++){scanf("%c",&a[i][j]);}}for(i=1;i<=n;i++){for(j=1;j<=m;j++){if(a[i][j]=='@'){count++;dfs(i,j);}}}printf("%d\n",count);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.