[搜索]广搜的两道题

来源:互联网 发布:信息清理软件 编辑:程序博客网 时间:2024/05/17 23:23

抓住那头牛(POJ3278)

广度优先搜索算法如下:(用QUEUE)
(1) 把初始节点S0放入Open表中;
(2) 如果Open表为空,则问题无解,失败 退出;
(3) 把Open表的第一个节点取出放入 Closed表,并记该节点为n;
(4) 考察节点n是否为目标节点。若是, 则得到问题的解,成功退出;
(5) 若节点n不可扩展,则转第(2)步;
(6) 扩展节点n,将其不在Closed表和 Open表中的子节点(判重)放入Open表的尾部 ,并为每一个子节点设置指向父节点的指针( 或记录节点的层次),然后转第(2)步。

#include <algorithm>#include <iostream>#include <map>#include <queue>#include <set>#include <string.h>#include <string>#include <vector>using namespace std;int MAXN = 100000;int N, K;struct Step {  int position;  int steps;  Step(int xx, int s) : position(xx), steps(s) {}};queue<Step> q;int main() {  cin >> N >> K;  bool visited[MAXN + 10];  memset(visited, 0, sizeof(visited));  visited[N] = true;  q.push(Step(N, 0));  while (!q.empty()) {    Step s = q.front();    visited[s.position] = true;    // q.pop();    if (s.position == K) {      cout << s.steps << endl;      return 0;    } else {      if (s.position - 1 >= 0 && !visited[s.position - 1]) {        q.push(Step(s.position - 1, s.steps + 1));        visited[s.position - 1] = true;      }      if (s.position + 1 <= MAXN && !visited[s.position + 1]) {        q.push(Step(s.position + 1, s.steps + 1));        visited[s.position + 1] = true;      }      if (s.position * 2 <= MAXN && !visited[s.position * 2]) {        q.push(Step(s.position * 2, s.steps + 1));        visited[s.position * 2];      }    }    q.pop();  }  return 0;}

迷宫问题 (POJ3984)

基础广搜。先将起始位置入队列
每次从队列拿出一个元素,扩展其相邻的4个元素入队列(要判重), 直到队头元素为终点为止。队列里的元素记录了指向父节点(上一步)的指针
队列不能用STL的queue或deque,要自己写。用一维数组实现,维护一个 队头指针和队尾指针。

思路很简单,注意优化下数据结构。

#include <algorithm>#include <iostream>#include <map>#include <queue>#include <set>#include <string.h>#include <string>#include <vector>using namespace std;int map1[5][5];bool visited[30][30];struct Node {  int x;  int y;} a[30];int dir[][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};bool judge(int X, int Y) {  if (X >= 0 && X <= 4 && Y >= 0 && Y <= 4 && !visited[X][Y] && !map1[X][Y])    return true;  else    return false;}void print(int n) {  int t = pre[n];  if (t == -1) {    printf("(0,0)\n");    return;  }  print(t);  printf("(%d,%d)\n", a[n].x, a[n].y);}void BFS() {  int head = 0, tail = 1;  a[0].x = 0;  a[0].y = 0;  pre[0] = -1;  while (head < tail) {    for (int i = 0; i < 4; i++) {      int newX = a[head].x + dir[i][0];      int newY = a[head].y + dir[i][1];      if (a[head].x == 4 && a[head].y == 4) {        print(head);        return;      }      if (!judge(newX, newY))        continue;      visited[newX][newY] = true;      a[tail].x = newX;      a[tail].y = newY;      pre[tail] = head;      tail++;    }    head++;  }}int main() {  int i, j;  for (i = 0; i < 5; i++) {    for (j = 0; j < 5; j++) {      scanf("%d", &map1[i][j]);    }  }  memset(visited, 0, sizeof(visited));  BFS();  return 0;}
0 0