广度优先搜索--BFS

来源:互联网 发布:淘宝分享社区 编辑:程序博客网 时间:2024/04/30 08:38

广度优先搜索

要求

迷宫另外一种解法

求迷宫中从坐标(0, 0)到(3,2)最少步数?

0代表路,1代表障碍物,2标识走过的路径,3代表目标点。

思路

将每走一步的下一步可能的值依次加入队列,在从队列中取出走下一步,重复以上动作,直到找到目标。

代码

#include <stdio.h>#define N 5#define M 4int a[N][M] = {                {0, 0,  1, 0},                {0, 0,  0, 0},                {0, 0,  1, 0},                {0, 1,  3, 0},                {0, 0,  0, 1}               };struct node{    int x;    int y;    int s;};struct node que[2501];  // 地图大小不超过50 * 50int head = 0, tail = 0;int book[N][M] = {0};void enqueue(struct node p) {    que[tail] = p;    tail++;}struct node dequeue(void) {    head++;    return que[head-1];}int is_empty(void) {    return head == tail;}void print_a() {    for (int i = 0; i < N; ++i)    {        for (int j = 0; j < M; ++j)        {            printf("%d ", a[i][j]);        }        printf("\n");    }    printf("\n");}void print_que() {    for (int i = head; i < tail; ++i) {        struct node p = que[i];        printf("(%d, %d, %d) ", p.x, p.y, p.s);    }    printf("\n");}int main() {    int step = 0;    struct node p = {0, 0, 1};    enqueue(p);    a[p.x][p.y] = 2;    while(!is_empty()) {        print_que();        p = dequeue();        printf("(%d %d %d) \n", p.x, p.y, p.s);        if ( (a[p.x][p.y+1] == 0 || a[p.x][p.y+1] == 3) && a[p.x][p.y+1] != 2 && p.y+1 < M ){            printf("right \n");            if (a[p.x][p.y+1] == 3){                printf("------------ %d\n", p.s);                break;            }            struct node k = {p.x, p.y+1, que[head-1].s + 1};            enqueue(k);            a[p.x][p.y+1] = 2;        }        if ( (a[p.x+1][p.y] == 0 || a[p.x+1][p.y] == 3) && a[p.x+1][p.y] != 2 && p.x+1 < N ){            printf("down \n");            if (a[p.x+1][p.y] == 3) {                printf("------------ %d\n", p.s);                break;            }            struct node k = {p.x+1, p.y, que[head-1].s + 1};            enqueue(k);            a[p.x+1][p.y] = 2;        }        if ( (a[p.x][p.y-1] == 0 || a[p.x][p.y-1] == 3) && a[p.x][p.y-1] != 2 && p.y-1 >= 0 ){            printf("left \n");            if (a[p.x][p.y-1] == 3) {                printf("------------ %d\n", p.s);                break;            }            struct node k = {p.x, p.y-1, que[head-1].s + 1};            enqueue(k);            a[p.x][p.y-1] = 2;        }        if ( (a[p.x-1][p.y] == 0 || a[p.x-1][p.y] == 3) && a[p.x-1][p.y] != 2 && p.x-1 >= 0 ){            printf("up \n");            if (a[p.x-1][p.y] == 3) {                printf("------------ %d\n", p.s);                break;            }            struct node k = {p.x-1, p.y, que[head-1].s + 1};            enqueue(k);            a[p.x-1][p.y] = 2;        }        print_a();    }    printf("--- end --\n");    return 0;}
0 0
原创粉丝点击