例题6-12 UVA572 Oil Deposits 基础dfs求连通块

题目连接:https://vjudge.net/problem/UVA-572

思路:基础dfs

Code:(紫书版本)

#include 
#include 
#include 
using namespace std;
const int AX = 1e2+5;
char mp[AX][AX];
int id[AX][AX];
int n , m;
void dfs( int r , int c , int idx ){
  if( r < 0 || r >= m || c < 0 || c >= n ) return ;
  if( id[r][c] || mp[r][c] != '@' ) return;
  id[r][c] = idx;
  for( int dr = -1 ; dr <= 1 ;dr++ ){
   for( int dc = -1 ; dc <= 1 ; dc++ ){
    if( dr || dc ) dfs( r + dr , c + dc , idx );
  } 
}
} 

int main(){
  while( ~scanf("%d%d",&m,&n) && n && m ){
    int cnt = 0;
    for( int i = 0 ; i < m ; i++ ) scanf("%s",mp[i]);
      memset(id,0,sizeof(id));
    for( int i = 0 ; i < m ; i++ ){
      for( int j = 0 ; j < n ; j++ ){
        if( id[i][j] == 0 && mp[i][j] == '@' ){
          dfs( i , j , ++cnt );
        }
      }
    }
    cout << cnt << endl;
  }
  return 0;
}

(方向数组版本):

Code:

#include
#include
#include
#include
using namespace std;
char oil[200][200];
int dir[8][2] = {
  {1,0},
  {-1,0},
  {0,1},
  {0,-1},
  {1,1},
  {-1,1},
  {1,-1},
  {-1,-1},
};
void dfs(int n,int m,int x,int y){
  for(int i=0;i<8;i++){
    int xx = x + dir[i][0];
    int yy = y + dir[i][1];
    if(xx>=0 && xx=0&&yy>n>>m){
    if(n==0&&m==0)  break;
    int ans = 0;
    for(int i=0;i>oil[i][j];
      }
    }
      for(int i=0;i


你可能感兴趣的:(图-DFS,算法竞赛入门经典-数据结构基础)