poj3278 一维bfs 水题

来源:互联网 发布:淘宝新店没生意怎么办 编辑:程序博客网 时间:2024/06/05 08:45
/*一维bfs,确定边界,标记数组,结构体包括坐标和当前步数*/
#include <cstdio>
#include <queue>
#include <cstring>
#define N 100005
using namespace std;
int vis[N];
typedef struct note {
 int x;//当前点坐标
 int s;//当前点已走步数
}point;
point start; int endd;
int isbroder(int x)
{
 return x >= 0 && x <= N;
}
int bfs(point s, int e)
{
 queue<point> q;
 while (!q.empty()) q.pop();
 q.push(s);
 vis[s.x] = 1;
 while (!q.empty())
 {
  point cur = q.front(); q.pop();
  if (cur.x == endd) return cur.s;//临界条件判断
  else//穷举三种走法
  {
   point t;
   if (isbroder(cur.x * 2) && !vis[cur.x * 2])
   {
    t.x = 2 * cur.x; t.s = cur.s + 1;
    vis[t.x] = 1;
    q.push(t);
   }
   
   if (isbroder(cur.x - 1) && !vis[cur.x - 1])
   {
    t.x = cur.x - 1; t.s = cur.s + 1;
    vis[t.x] = 1;
    q.push(t);
   }
   if (isbroder(cur.x + 1) && !vis[cur.x + 1])
   {
    t.x = cur.x + 1; t.s = cur.s + 1;
    vis[t.x] = 1;
    q.push(t);
   }
  }
 }
 return -1;//查找失败
}
int main()
{
 while (scanf("%d%d", &start.x, &endd) != EOF)
 {
  memset(vis, 0, sizeof(vis));
  start.s = 0;
  int ans;
  ans = bfs(start,endd);
  printf("%d\n", ans);
 }
 return 0;
}
0 0
原创粉丝点击