您的位置:首页 > 其它

[挑战程序设计竞赛] POJ 3009 - Curling 2.0

2014-11-27 16:08 387 查看
题目大意:

给定起点和终点的位置,从起点开始朝一个方向扔石头,当石头碰到一个方块,会停止在方块的前一个位置,并且这个方块会消失。

当石头在一个方向上没有碰到任何方块,石头会飞到Board外,则游戏失败。求出从起点开始扔石头,是否能在10次以内碰到终点的位置。

能则输出最少的次数,不能则输出-1。

由于题目只询问10次以内是否能碰到终点的位置。那DFS的复杂度就没有多大了。。

直接枚举起点的四个方向,会得到四个静止状态……重复枚举即可,求最小次数,也就是求有解时递归的最小深度。。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <assert.h>
#include <time.h>
typedef long long LL;
const int INF = 500000001;
const double EPS = 1e-9;
const double PI = acos(-1.0);
using namespace std;
int w, h, dir[4][2] = {-1,0, 1,0, 0,-1, 0,1};   // 方向数组
int graph[50][50], temp[50][50], ans;
bool check(int x, int y, int k)  // 检查越界
{
if(k == 0 || k == 1)
{
if(x <= 1 || x >= h)
{
return false;
}
}
else if(y <= 1 || y >= w)
{
return false;
}
return true;
}
void dfs(int x, int y, int deep)
{
if(deep >= 10) return false;
for(int i = 0; i < 4; i++)  // 枚举每个位置的四个方向
{
int xx = dir[i][0] + x;
int yy = dir[i][1] + y;
if(graph[xx][yy] != 1)
{
while(graph[xx][yy] != 1)
{
if(graph[xx][yy] == 3)
{
ans = min(ans, deep);
}
xx = dir[i][0] + xx;
yy = dir[i][1] + yy;
}
xx -= dir[i][0];
yy -= dir[i][1];
if(check(xx, yy, i))
{
graph[xx+dir[i][0]][yy+dir[i][1]] = 0; // 撞到后的方块会消失
dfs(xx, yy, deep + 1);
graph[xx+dir[i][0]][yy+dir[i][1]] = temp[xx+dir[i][0]][yy+dir[i][1]];  // 当前状态搜索完毕后把方块恢复
}
}
}
}
void init()   // 初始化边界
{
for(int i = 0; i < 50; i++)
{
for(int j = 0; j < 50; j++)
{
graph[i][j] = 1;
}
}
}
int main()
{
//freopen("test0.in", "r", stdin);
//freopen("test0.out", "w", stdout);
//srand(time(NULL));
int x, y;
while(~scanf("%d %d", &w, &h), w&&h)
{
init();
ans = 10000;
for(int i = 1; i <= h; i++)
{
for(int j = 1; j <= w; j++)
{
scanf("%d", &graph[i][j]);
if(graph[i][j] == 2)
{
x = i;
y = j;
}
}
}
memcpy(temp, graph, sizeof(graph));
dfs(x, y, 0);
if(ans != 10000)
{
printf("%d\n", ans+1);
}
else
{
printf("-1\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息