POJ 3009 *** Curling 2.0

本文介绍了一种利用深度优先搜索(DFS)和回溯算法来解决棋盘上冰球从起始位置出发,沿着上下左右四个方向运动,直至遇到冰块或出界的问题。通过不断尝试不同的路径,最终找到从起始位置到达目标位置的最短路径,限制最多只能打碎10次冰块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:有一个h*w的棋盘,某些棋盘上的位置有冰块。打冰球的游戏,对于冰球而言只能向上下左右运动,且会一直运动直到遇到有冰块的位置,或者出界。如果遇到有冰块的位置,则将冰块打碎,冰球停留在往冰块方向上的前一个位置上。如果出界则出局。问最短到达目标需要多少步。(最多只能打10次)


想法:dfs+回溯。


代码如下:


#pragma warning(disable:4996)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<stack>
#include<queue>
#include<cstring>
#include<sstream>
#include<set>
#include<string>
#include<iterator>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct Position {
	int x, y;
};//当前位置
int w, h, cnt;
int maze[30][30];
int dir[4][2] = { { 0, -1 },{ -1, 0 },{ 0, 1 },{ 1, 0 } };
Position start;
void dfs(Position start,int step) {//step记录走了多少步
	for (int d = 0; d < 4; ++d) {//4个方向
		Position temp,temp2;
		temp.x = start.x + dir[d][0];
		temp.y = start.y + dir[d][1];
		if (step<cnt-1&&temp.x > 0 && temp.x <= h&&temp.y > 0 && temp.y <= w&&maze[temp.x][temp.y] !=1) {//判断冰球最初位置周围是否可走,其中step<cnt-1保证了此刻的cnt最小
			while (temp.x > 0 && temp.x <= h&&temp.y > 0 && temp.y <= w&&maze[temp.x][temp.y] == 0) {//如果可走,那么一直行进到遇见冰块或者出界
				temp.x += dir[d][0];
				temp.y += dir[d][1];}
			temp2.x = temp.x - dir[d][0];
			temp2.y = temp.y - dir[d][1];
			if (temp.x > 0 && temp.x <= h&&temp.y > 0 && temp.y <= w) {//如果是遇见了冰块,那么进行下一步搜索
				if (maze[temp.x][temp.y] == 3)
					cnt = step + 1;
				if (maze[temp.x][temp.y] == 1) {
					maze[temp.x][temp.y] = 0;//已到达,冰块消失
					dfs(temp2, step + 1);//搜索该位置
					maze[temp.x][temp.y] = 1;//维护原始数组
				}
			}
		}
	}
}
int main(void) {
	while(cin >> w >> h,w||h) {
		for (int i = 1; i <= h; ++i)
			for (int j = 1; j <= w; ++j) {
				cin >> maze[i][j];
				if (maze[i][j] == 2) {//整合输入,因为起点事实上在过程中也可达,故直接将起点记录且将起点设置为0
					start.x = i,start.y = j;
					maze[i][j] = 0;
				}
			}
		cnt = 11;
		dfs(start, 0);
		if (cnt>10)cout << -1 << endl;
		else cout << cnt << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值