poj3083

dfs+bfs,由于bfs的时候忘了加vis判断是否已入队,而多次超内存。

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
   
#include < iostream >
#include
< cstdlib >
#include
< cstring >
#include
< cstdio >
#include
< queue >
using namespace std;

#define maxn 45

struct XPoint
{
int x, y, d;
XPoint(
int xx, int yy, int dd) :
x(xx), y(yy), d(dd)
{
}
XPoint()
{
}
} s, e;

int dir[ 4 ][ 2 ] = // r, u, l, d
{
{
0 , 1 },
{
- 1 , 0 },
{
0 , - 1 },
{
1 , 0 } };
bool map[maxn][maxn];
bool vis[maxn][maxn];
int n, m;
int ansl, ansr, ans;

bool ok( int x, int y)
{
if (x >= n || x < 0 || y >= m || y < 0 )
return false ;
if ( ! map[x][y])
return false ;
return true ;
}

void input()
{
scanf(
" %d%d " , & m, & n);
getchar();
for ( int i = 0 ; i < n; i ++ )
{
for ( int j = 0 ; j < m; j ++ )
{
char ch;
scanf(
" %c " , & ch);
if (ch == ' . ' )
map[i][j]
= true ;
else
map[i][j]
= false ;
if (ch == ' S ' )
{
s.x
= i;
s.y
= j;
}
if (ch == ' E ' )
{
e.x
= i;
e.y
= j;
map[i][j]
= true ;
}
}
getchar();
}
if (s.x == 0 )
s.d
= 3 ;
if (s.x == n - 1 )
s.d
= 1 ;
if (s.y == 0 )
s.d
= 0 ;
if (s.y == m - 1 )
s.d
= 2 ;
}

void dfs(XPoint a, int step, int dc)
{
if (a.x == e.x && a.y == e.y)
{
ans
= step;
return ;
}
for ( int i = - 1 ; i < 3 ; i ++ )
{
int x, y, d;
d
= (a.d + i * dc + 4 ) % 4 ;
x
= a.x + dir[d][ 0 ];
y
= a.y + dir[d][ 1 ];
if (ok(x, y))
{
dfs(XPoint(x, y, d), step
+ 1 , dc);
break ;
}
}
}

void bfs()
{
int x, y;
memset(vis,
0 , sizeof (vis));
queue
< XPoint > q;
s.d
= 1 ;
q.push(s);
while ( ! q.empty())
{
XPoint temp
= q.front();
q.pop();
for ( int i = 0 ; i < 4 ; i ++ )
{
x
= temp.x + dir[i][ 0 ];
y
= temp.y + dir[i][ 1 ];
if (e.x == x && e.y == y)
{
ans
= temp.d + 1 ;
return ;
}
if (ok(x, y) && ! vis[x][y])
{
q.push(XPoint(x, y, temp.d
+ 1 ));
vis[x][y]
= true ;
}
}
}
}

int main()
{
// freopen("D:\\t.txt", "r", stdin);
int t;
scanf(
" %d " , & t);
while (t -- )
{
input();
dfs(s,
1 , - 1 );
ansl
= ans;
dfs(s,
1 , 1 );
ansr
= ans;
bfs();
printf(
" %d %d %d\n " , ansl, ansr, ans);
}
return 0 ;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值