HDU T1312 Red and Black

版权声明:希望能帮到弱校的ACMer成长,因为自己是弱校菜鸡~~~~ https://blog.csdn.net/Mr__Charles/article/details/82142600

                          HDU T1312 Red and Black


题解:

    因为是遍历所有可以走的点,所以不需要回溯。需要注意的是写完要测试最小值

    例如:1 1

               @

    答案应该为1,本身也算一个。

Dfs代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#define INF 0x3f3f3f3f
#define maxn 25
using namespace std;

int w,h,ans;
int mov[4][2] = {-1,0,0,1,1,0,0,-1};
char maps[maxn][maxn];
bool vis[maxn][maxn];

bool charge(int x,int y){
	if(x > h-1 || x < 0 || y > w-1 || y < 0 || maps[x][y] == '#')
	    return false;
	return true;
}

void Dfs(int x,int y){
	int nowx = x;
	int nowy = y;
	for(int i = 0; i < 4; ++i){
		int nexx = nowx + mov[i][0];
		int nexy = nowy + mov[i][1];
		if(charge(nexx,nexy) && !vis[nexx][nexy]){
			vis[nexx][nexy] = true;
			Dfs(nexx,nexy);
			ans++;
		}
	}
}

int main(){
	int x,y;
	while(scanf("%d%d",&w,&h),w+h){
		ans = 1;
		for(int i = 0; i < h; ++i){
			scanf("%s",&maps[i]);
			for(int j = 0; j < w; ++j){
		        if(maps[i][j] == '@'){
		        	x = i;y = j;
		        }
		        vis[i][j] = false;
		    }
		}
		vis[x][y] = true;
	    Dfs(x,y);
	    printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Mr__Charles/article/details/82142600