Nightmare hdu 1072 bfs (可以往回走的bfs,hash有点帅)

 

/*
   方法借鉴了hdOj论坛,没有处理过可以往回走的题目,所以处理起来很棘手,
   第一次爆内存了,对于输出是-1的情况的,我起初考虑的是有点问题的,但是不知怎么解决
   后来看了论坛,想想应该是自己的代码造成死循环的缘故吧。
   bfs的变形真的让人有点那个的。。
*/
#include<iostream>//2399633 2010-04-29 19:31:23 Accepted 1072 0MS 292K 1915 B C++ 悔惜晟
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;

int si, sj;
int ei, ej;
int num;
int n, m;
char map[10][10];
int  hash[10][10];//这个hash 有点帅。。。
int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
struct node
{
 int time;
 int x;
 int y;
 //int count;
};

int bfs(int sx, int sy)
{
 node N, P;
 int i;
 queue<node>q;
 N.x = sx;
 N.y = sy;
 N.time = 0;
 hash[N.x][N.y] = 6;//完美的处理
 //N.count = 6;
 q.push(N);
 while(!q.empty())
 {
  N = q.front();
  /*
  if(N.x == ei && N.y == ej && hash[N.x][N.y] > 0)
  {
   printf("%d/n", N.time);
   return 1;
  }
  */
  /*
  if(N.time >= num)
  {
   break;
  }
  */
  q.pop();
  for(i = 0; i < 4; i++)
  {
   P.x = N.x + dir[i][0];
   P.y = N.y + dir[i][1];
   //P.count = N.count - 1;
   P.time = N.time + 1;
   if(hash[N.x][N.y] <= 1 || P.x < 0 || P.x >= n || P.y < 0 || P.y >= m || map[P.x][P.y] == '0')
    continue;
   /*
   if(map[P.x][P.y] == '1' || map[P.x][P.y] == '3')
   {
    q.push(P);
    if(hash[P.x][P.y] < hash[N.x][N.y] - 1)
        hash[P.x][P.y] = hash[N.x][N.y] - 1;
     
   }
   */
   if(map[P.x][P.y] == '3')
   {
    printf("%d/n", P.time);
    return 1;
   }
   if(hash[P.x][P.y] < hash[N.x][N.y] - 1)
   {
    hash[P.x][P.y] = hash[N.x][N.y] - 1;
    if(map[P.x][P.y] == '4')
    {
     //P.count = 6;
     hash[P.x][P.y] = 6;
     //q.push(P);
    }
    q.push(P);
   }


  }

 }
 printf("-1/n");
 return 1;

}

int main()
{
 int T;
 int i, j;
 cin>>T;
 while(T--)
 {
  cin>>n>>m;
  for(i = 0; i < n; i++)
  for(j = 0 ; j <m; j++)
  {
   cin>>map[i][j];
   //hash[i][j] = 6;
   if(map[i][j] == '2')
   {
    si = i;
    sj = j;
   }
   if(map[i][j] == '3')//没有用的
   {
    ei = i;
    ej = j;
   }
  }
  //num =2 * (int)(abs(1.0 * si - ei) +abs(1.0 * sj - ej));
  memset(hash, -1, sizeof(hash));
  bfs(si, sj);
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值