zoukankan      html  css  js  c++  java
  • Lake Counting (DFS)

    N*M的园子,雨后积起了水.八连通的积水背认为是连接在一起的.请求出园子里总共有多少水洼?

    dfs(Depth-First  Search)  八个方向的简单搜索....

    深度优先搜索从最开始的状态出发,遍历所有可以到达的状态.由此可以对所有的状态进行操作,或者列举出所有的状态.

     1 int N,M;
     2 char field[50][50];
     3 
     4 void dfs(int x,int y)
     5 {
     6     field[x][y]=='.';  //将现在所在位置替换
     7     for(int dx=-1; dx<=1; dx++){
     8         for(int dy=-1; dy<=1; dy++){    //向x方向移动dx,向y方向移动dy,移动的结果为(nx,ny)
     9             int nx=x+dx;
    10             int ny=y+dy;
    11             if(0<=nx && nx<N && 0<ny && ny<M && field[nx][ny]=='W')  //判断(nx,ny)是不是在园子内,以及是否有积水
    12                 dfs(nx,ny);
    13         }
    14     }
    15 }
    16 
    17 void solve(){
    18     int ans=0;
    19     for(int i=0; i<N; i++){
    20         for(int j=0; j<M; j++){
    21             if(field[i][j]=='W'){   //从有W的地方开始dfs
    22                 dfs(i,j);
    23                 ans++;
    24             }
    25         }
    26     }
    27     printf("%d
    ",ans);
    28 }
  • 相关阅读:
    155. 最小栈
    160. 相交链表
    PAT 1057 Stack
    PAT 1026 Table Tennis
    PAT 1017 Queueing at Bank
    PAT 1014 Waiting in Line
    PAT 1029 Median
    PAT 1016 Phone Bills
    PAT 1010 Radix
    PAT 1122 Hamiltonian Cycle
  • 原文地址:https://www.cnblogs.com/wangmengmeng/p/5222921.html
Copyright © 2011-2022 走看看