//============================================================================
// Name : POJ_3083_DFS+BFS.cpp
// Author : tiger
// Version :
// Copyright : Your copyright notice
// Description : short path 用BFS,left or right strategy用DFS
// left优先是当进入一个新位置后,下一步先选自己左手边,不通再顺时针继续选;
// right优先是先选右手边,不通再逆时针选择
//============================================================================
#include <queue>
#include <stdio.h>
#include <iostream>
using namespace std;
char map[41][41];
bool visited[41][41];
int dir[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
int num;
int w,h;
bool Left;
struct point{
int x,y;
int steps;
};
bool available(int x,int y)
{
if(x < 0 || x >= h || y < 0 || y >= w || '#' == map[x][y] )
return false;
return true;
}
int bfs(int x,int y)
{
visited[x][y] = true;
point s,t;
s.x = x;
s.y = y;
s.steps = 1;
queue<point> q;
q.push(s);
while(true)
{
s = q.front();
q.pop();
t.steps = s.steps + 1;
for(int i =0; i < 4; i++)
{
t.x = s.x + dir[i][0];
t.y = s.y + dir[i][1];
if(available(t.x,t.y) && !visited[t.x][t.y])
{
if('E' == map[t.x][t.y])
return t.steps;
q.push(t);
visited[t.x][t.y] = true;
}
}
}
return 0;
}
bool dfs(int x,int y,int direct)
{
num++;
if('E' == map[x][y])
return true;
if(Left)//如果左优先,把方向左调整两个
{
direct = (direct - 1 + 4) % 4;//方向逆时针转一
direct = (direct - 1 + 4) % 4;
}else
{
direct = (direct + 1) % 4;//方向顺时针转一
direct = (direct + 1) % 4;//方向顺时针转一
}
for(int i = 0; i < 4; i++)
{
if(Left)
direct = (direct + 1) % 4;//方向顺时针转一
else
direct = (direct - 1 + 4) % 4;//方向逆时针转一
if(available(x+dir[direct][0],y+dir[direct][1]) )
{
if( dfs(x+dir[direct][0],y+dir[direct][1],direct))
return true;
}
}
return false;
}
int main() {
freopen("in","r",stdin);
int n;
//scanf("%d",&n);
cin >> n;
int i,j,x,y,direct;
while(n--)
{
//scanf("%d %d",&w,&h);
cin >> w >> h;
for(i = 0; i < h; i++)
{
//getchar();
for(j = 0; j < w; j++)
{
//scanf("%c",&map[i][j]);
cin >> map[i][j];
visited[i][j]= false;
if('S' == map[i][j])
{
x = i;
y = j;
}
}
}
num = 0;
if(x == 0)
direct = 3;
else if(y == 0)
direct = 2;
else if(x == h-1)
direct = 1;
else if(y == w-1)
direct = 0;
Left = true;
num = 0;
dfs(x,y,direct);
printf("%d ",num);
Left = false;
num = 0;
dfs(x,y,direct);
printf("%d ",num);
printf("%d/n",bfs(x,y));
}
return 0;
}
POJ_3083_DFS+BFS
最新推荐文章于 2020-02-23 20:51:29 发布