红与黑,,

这是一个C++程序,它读取一个二维矩阵,然后使用深度优先搜索(DFS)算法从指定的起点开始遍历矩阵中的空白(.),计算可到达的区域数量。程序首先定义了点结构体和DFS函数,接着在主函数中进行矩阵输入和遍历操作。
摘要由CSDN通过智能技术生成

 #include <bits/stdc++.h>

using namespace std;

int w,h;

int cnt;

char a[21][21];

 

struct point{

 int x;

 int y;

};

 

point a1;

bool in(point t){

 if(t.x>=0&&t.x<h&&t.y>=0&&t.y<w){

  return true;

 }

 else{

  return false;

 }

}

int dir[4][2]={{-1,0},{0,-1},{1,0},{0,1}};

bool vis[21][21];

 void dfs(point a1){

  point t;

  

  for(int i=0;i<4;i++){

   t.x=a1.x+dir[i][0];

   t.y=a1.y+dir[i][1];

   if(!in(t)){

    continue;

   }

   if(!vis[t.x][t.y]&&a[t.x][t.y]=='.'){

    cnt++;

    vis[t.x][t.y]=true;

    

    dfs(t);

   }

    }    

// if(n==0){

// return;

// }

}

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

 

int main(int argc, char** argv) 

{

 memset(vis,0,sizeof(vis));

 cin>>w>>h;

 while(w!=0&&h!=0){

  cnt=1; 

  for(int i=0;i<h;i++){

  for(int j=0;j<w;j++){

   cin>>a[i][j];

   vis[i][j]=false;

   if(a[i][j]=='@'){

    a1.x=i;

    a1.y=j;

   }

  }

 }

 dfs(a1);

    cout<<cnt;

    cout<<endl;

 cin>>w>>h;

 

}

 

 

 return 0;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值