题目描述
Red and Black
大意是只能走周围的4个相邻点,只能走黑色点,不能走红色点
输出最多可以走多少个不同的黑色点
题目思路
- DFS
- 往四个方向走,走过的点标记一下
- 碰到红色点或者越界或者标记过的点,是DFS的终止条件
代码
- 第一种解法
#include <iostream>
#include<stdio.h>
using namespace std;
#define N 100
char rb[N][N];
bool mark[N][N];
void dfs(int n,int m,int& res,int x,int y){
if(mark[x][y]||rb[x][y]=='#'||x<0||x>n-1||y<0||y>m-1){
return;
}
mark[x][y]=true;
res+=1;
dfs(n,m,res,x-1,y);
dfs(n,m,res,x+1,y);
dfs(n,m,res,x,y-1);
dfs(n,m,res,x,y+1);
}
int main() {
freopen("in.txt","r",stdin);
int n,m,sx,sy,res;
while(1){
cin>>m>>n;
if(m==0&&n==0) break;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>rb[i][j];
if(rb[i][j]=='@'){
sx=i,sy=j;
}
mark[i][j]=false;
}
}
res=0;
dfs(n,m,res,sx,sy);
cout<<res<<endl;
}
fclose(stdin);
return 0;
}
- 第二种解法(更通用)
#include <iostream>
#include<stdio.h>
using namespace std;
#define N 21
char rb[N][N];
bool mark[N][N];
const int direct[4][2]={
{1,0},
{-1,0},
{0,1},
{0,-1}
};
void dfs(int n,int m,int x,int y,int &step){
if(rb[x][y]=='#'||mark[x][y]||x<0||x>n-1||y<0||y>m-1){
return;
}
step++;
mark[x][y]=true;
for(int d=0;d<4;d++){
int rx=x+direct[d][0];
int ry=y+direct[d][1];
dfs(n,m,rx,ry,step);
}
}
int main() {
freopen("in.txt","r",stdin);
int n,m,sx,sy,step;
while(1){
cin>>m>>n;
if(n==0&&m==0){
break;
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>rb[i][j];
mark[i][j]=false;
if(rb[i][j]=='@'){
sx=i;
sy=j;
}
}
}
step=0;
dfs(n,m,sx,sy,step);
cout<<step<<endl;
}
fclose(stdin);
return 0;
}