POJ 3009 Curling 2.0(开拓思路的dfs)

版权声明:听说这里让写版权声明~~~ https://blog.csdn.net/m0_37691414/article/details/82153825

题目大意:一个球只能走直线,切只能在碰到石头的时候才能停下来;而被碰到的石头将会消失;走一次直线只算一步,求最少步数;

这道题呢,颠覆了我以前的思考,总觉得BFS和DFS只能一步一步向旁边走一步,却不知道还可以搜直线,而且一次搜到底部
题目给了一个条件就是当步数打不10时就认为是不能走到了,这复杂度就有了大大的减小;所以直接暴力每条路径搜完也不会超时

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int map[30][30];
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};
int step, steps, h, w, sx, sy, ex, ey;
void dfs(int x, int y){
	if(step > 10)	return;
	for(int i = 0; i < 4; ++i){
		bool flag = false;
		int nx = x + dir[i][0];
		int ny = y + dir[i][1];
		while(nx >= 0 && nx < h && ny >= 0 && ny < w && map[nx][ny] != 1){
			flag = true;
			if(nx == ex && ny == ey && step < steps)
				steps = step;
			nx += dir[i][0];
			ny += dir[i][1];
		}
		if(map[nx][ny] == 1 && flag){
			step++;
			map[nx][ny] = 0;
			dfs(nx - dir[i][0], ny - dir[i][1]);
			step--;
			map[nx][ny] = 1;
		}
	}
}
int main(){
	while(~scanf("%d%d", &w, &h) && w && h){
		memset(map, 0, sizeof(map));
		for(int i = 0; i < h; ++i){
			for(int j = 0; j < w; ++j){
				scanf("%d", &map[i][j]);
				if(map[i][j] == 2)	sx = i, sy = j;
				if(map[i][j] == 3) 	ex = i, ey = j;
			}
		}
		steps = 0x3f3f3f3f;
		step = 1;
		dfs(sx, sy);
		printf("%d\n",steps>10?-1:steps);
	}
}

猜你喜欢

转载自blog.csdn.net/m0_37691414/article/details/82153825