zoukankan      html  css  js  c++  java
  • HDU 1241 连通块问题(DFS入门题)

    Input

    The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
     
    Output
    For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
     
    Sample Input
    1 1
    *
    3 5
    *@*@*
    **@**
    *@*@*
    1 8
    @@****@*
    5 5 
    ****@
    *@@*@
    *@**@
    @@@*@
    @@**@
    0 0 
    Sample Output
    
    
    
    

    这题还是比较好理解的,有着重叠的子问题,调用递归即可,感觉和DP有点不同,

    DP重叠子问题后会有状态的转移,这个只用递归即可。(个人理解,刚学,比较菜)

     1 #include<bits/stdc++.h>
     2 using namespace std ;
     3 
     4 char a[105][105];
     5 void DFS(int x, int y)
     6 {
     7     a[x][y]=0;
     8     int X[8]={-1,-1,0,1,1,1,0,-1};
     9     int Y[8]={0,1,1,1,0,-1,-1,-1};
    10     for(int k=0; k<8; k++){
    11         int i=x+X[k];
    12         int j=y+Y[k];
    13         if(a[i][j]=='@'){
    14             DFS(i,j);
    15         }
    16     }
    17 }
    18 int main ()
    19 {
    20     int n,m;
    21     while(cin>>n>>m)
    22     {
    23         if(n==0&&m==0)
    24             break;
    25 
    26         memset(a, 0, sizeof(a));
    27         for(int i=0; i<n; i++)
    28             for(int j=0; j<m; j++)
    29                 cin>>a[i][j];
    30 
    31         int cnt=0;
    32         for(int i=0; i<n; i++)
    33             for(int j=0; j<m; j++)
    34              if(a[i][j]=='@'){
    35                 cnt++;
    36                 DFS(i,j);
    37             }
    38         cout<<cnt<<endl;
    39     }
    40     return 0;
    41 }
     
  • 相关阅读:
    electron之打包成安装程序
    electron之环境安装、启动程序
    微信支付.net官方坑太多,我们来精简
    微信支付官方.net版之坑你没商量
    程序员出路在何方
    简单介绍
    mac中显示隐藏文件
    sublime Text 3 安装emmet
    Andriod学习笔记5:通过NDK在C++中实现日志输出
    Andriod学习笔记4:mac下搭建 Eclipse+CDT 集成开发环境
  • 原文地址:https://www.cnblogs.com/Yokel062/p/10183024.html
Copyright © 2011-2022 走看看