您的位置:首页 > 其它

POJ - 3009 Curling 2.0

2017-11-26 13:54 239 查看
这是一个简单的BFS题目

当step>10时直接剪枝可以减少运算量

dfs结束进行回溯

用bfs有些复杂

因为棋盘是不断的在变化的

#include<iostream>
using namespace std;
#define MAX_H 30
#define MAX_W 30
void input(int w, int h);
void dfs(int sx, int sy, int d);
int minstep,w,h;
int dir[4][2] = { {0,1},{-1,0},{0,-1},{1,0} };
int sx, sy,maze[MAX_H][MAX_W];
int main()
{
freopen("D:\\test.txt", "r", stdin);
while (cin >> w >> h&&w&&h)
{
minstep = 11;
input(w,h);
dfs(sx, sy, 0);
if (minstep < 11)
cout << minstep << endl;
else
cout << "-1" << endl;
}
}
void input(int w, int h)
{
int i, j;
for (i = 0; i < h; i++)
{
for (j = 0; j < w; j++)
{
cin >> maze[i][j];
if (maze[i][j] == 2)
{
sx = i, sy = j;
maze[sx][sy] = 0;
}
}
}
}

void dfs(int sx, int sy, int d)
{
if (d > minstep || d > 11)
return;
int i;
for (i = 0; i < 4; i++)
{

int row, col;
row = sx + dir[i][0];
col = sy + dir[i][1];
if (maze[row][col] == 1)
continue;
while (row >= 0 && row < h&&col >= 0 && col < w&&maze[row][col]==0)
{

row += dir[i][0];
col += dir[i][1];
}
if (row < 0 || row >= h || col < 0 || col >= w)
continue;
if (maze[row][col] == 1)
{
maze[row][col] = 0;
dfs(row-dir[i][0], col-dir[i][1], d + 1);
maze[row][col] = 1;
}
if (maze[row][col] == 3)
{
if (++d < minstep)
minstep = d;
return;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj dfs