bfs中的队列相关函数

成员函数:

empty()判断队列空,当队列空时,返回true。
size()访问队列中的元素个数。
push()会将一个元素置入queue中。
front()会返回queue内的第一个元素(也就是第一个被置入的元素)。
back()会返回queue中最后一个元素(也就是最后被插入的元素)。

pop()会从queue中移除一个元素。


注意:

     pop()虽然会移除下一个元素,但是并不返回它,front()和back()返回下一个元素但并不移除该元素。


定义优先队列    priority_queue<node> Q;    
与普通队不同的是,取出首位元素不是Q.front(),而是使用Q.top();
struct  node
 { 
int x,y,step; 
friend bool operator<(node n1,node n2)
 
//大于是从小到大 
return n1.step>n2.step; 

};

队列还有双向队列,其中双向队列可以使用到一些组合的成员函数。

如:

   队列名.pop_back();

   队列名.pop_front();

指的就是,删除队列开始的一个元素,或者删除队列结尾的一个元素。


下面是一个大神级总结队列。

双向队列:http://blog.csdn.net/morewindows/article/details/6946811


单向队列:  http://blog.csdn.net/morewindows/article/details/6950917


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于队列实现BFS算法的C语言代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_QUEUE_SIZE 1000 typedef struct { int x; int y; } Point; typedef struct { Point data[MAX_QUEUE_SIZE]; int front; int rear; } Queue; void initQueue(Queue *q) { q->front = -1; q->rear = -1; } int isEmpty(Queue *q) { return (q->front == -1 && q->rear == -1); } int isFull(Queue *q) { return (q->rear + 1) % MAX_QUEUE_SIZE == q->front; } void enqueue(Queue *q, Point p) { if (isFull(q)) { printf("Error: Queue is full!\n"); exit(EXIT_FAILURE); } if (isEmpty(q)) { q->front = q->rear = 0; } else { q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; } q->data[q->rear] = p; } Point dequeue(Queue *q) { if (isEmpty(q)) { printf("Error: Queue is empty!\n"); exit(EXIT_FAILURE); } Point p = q->data[q->front]; if (q->front == q->rear) { q->front = q->rear = -1; } else { q->front = (q->front + 1) % MAX_QUEUE_SIZE; } return p; } void bfs(int **graph, int n, int start) { Queue q; initQueue(&q); int visited[n]; for (int i = 0; i < n; i++) { visited[i] = 0; } Point p = {start, 0}; visited[start] = 1; enqueue(&q, p); while (!isEmpty(&q)) { Point curr = dequeue(&q); printf("%d ", curr.x); for (int i = 0; i < n; i++) { if (graph[curr.x][i] == 1 && visited[i] == 0) { Point next = {i, curr.y + 1}; visited[i] = 1; enqueue(&q, next); } } } } int main() { int n = 8; int **graph = (int **)malloc(n * sizeof(int *)); for (int i = 0; i < n; i++) { graph[i] = (int *)malloc(n * sizeof(int)); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = 0; } } graph[0][1] = graph[1][0] = 1; graph[0][2] = graph[2][0] = 1; graph[1][3] = graph[3][1] = 1; graph[1][4] = graph[4][1] = 1; graph[2][5] = graph[5][2] = 1; graph[2][6] = graph[6][2] = 1; graph[4][7] = graph[7][4] = 1; bfs(graph, n, 0); return 0; } ``` 该代码是一个简单的BFS实现,图的邻接矩阵存储在一个二维数组函数 `bfs` 接受该二维数组、顶点数和起点编号作为参数,并输出遍历结果。在函数使用了一个队列来辅助实现BFS。具体实现可参考代码注释。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值