專題一 簡單搜尋 Problem L

來源:互聯網
上載者:User

標籤:

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1241

題目大意:給定一個方格,有的點是‘@’,有的點是‘*’。若以一個‘@’為中心的3*3的矩陣中,其他‘@’和該‘@’屬於同一地區。

     求方格中一共有多少地區。

解題思路:dfs深搜

     遍曆每一個點,如果該點可以向深擴充,則分別向8個方向擴充,以此類推,直到遞迴結束。

     遞迴結束後,地區數目加一,所以和該點有“關係”的點都被標記。然後判斷其他可擴充的點。

代碼如下:

 1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4  5 #define MAXN 105 6  7 int m,n; 8 char Map[MAXN][MAXN];//描述該方格 9 int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,1},{0,-1},{1,1},{1,0},{1,-1}};//描述方向10 11 void dfs(int x,int y)12 {13     Map[x][y]=‘*‘;//將每點標記為不可擴充(已經經過)14 15     int dx,dy;16     for(int i=0;i<8;i++)//向8個方向進行擴充17     {18         dx=x+dir[i][0];19         dy=y+dir[i][1];20         if(dx<0 || dx>=m || dy<0 ||dy>=n)//判斷是否在方格內部21         {22             continue;23         }24         if(Map[dx][dy]==‘@‘)//如果該點可以擴充,遞迴25         {26             dfs(dx,dy);27         }28     }29 }30 31 int main()32 {33     int sum;34     while(cin>>m>>n)35     {36         cin.get();//!!!!!!!!!!!!!!!!37         if(m==0) break;38 39         for(int i=0;i<m;i++)40         {41             for(int j=0;j<n;j++)42             {43                 cin>>Map[i][j];//!!!!!!!!!!!!!!!!44             }45             cin.get();//!!!!!!!!!!!!!!!!46         }47 48         sum=0;49         for(int i=0;i<m;i++)//遍曆整個矩陣50         {51             for(int j=0;j<n;j++)52             {53                 if(Map[i][j]==‘@‘)54                 {55                     dfs(i,j);56                     sum++;57                 }58             }59         }60         printf("%d\n",sum);61     }62     return 0;63 }
View Code

 

專題一 簡單搜尋 Problem L

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.