C++U4-第08课-队列

发布时间 2023-12-11 14:46:49作者: 小虾同学

队列:顺序队列

 队列基本操作

 选择题1

 选择题2

 程序阅读题

 

 

 

 

 打疫苗

 

【算法分析】
用数组实现队列,按题意模拟即可。

【参考代码】
#include <iostream>
using namespace std;

string q[1010]; 
int f, r; //f前端,指向队头,r后端,指向队尾的后一个位置 ,初始为0 

void push(string x){  //入队 
    q[r++] = x;
}

void pop(){    //出队 
    f++;
} 

string front(){  //返回队首元素 
    return q[f];
} 

bool empty(){ //队空 
    return f == r;
} 

int main(){
    while(true){
        string s;
        cin >> s;
        if(s[0] == '1'){
            push(s);
        } else if(s == "out"){
            int t;
            cin >> t;
            if(!empty()){
                while(!empty() && t > 0){
                    cout << front() << " ";
                    pop();
                    t--;
                }
            } else cout << "empty";
            cout << endl;
        } else if(s == "end"){
            while(!empty()){
                cout << front() << " ";
                pop();
            }
            break;
        }
    }
    return 0;
}
View Code

 

循环队列

 

 

 

 

 程序阅读题打疫苗2

 

 

 

 

 

 

 阵列数字搜索

 

#include <iostream>
using namespace std;

// 定义节点结构体,包含x和y坐标
struct node {
    int x, y;
};

node q[10005]; // 定义队列q,用于存放节点
int f, r; // 队列的头和尾指针
int n; // 网格大小
bool vis[110][110]; // 记录节点是否被访问过
int Map[110][110]; // 存放网格地图的数组
int dir[4][2] = { -1, 0, 1, 0, 0, -1, 0, 1 }; // 上下左右四个方向的偏移量

void push(node t) {
    q[r].x = t.x;
    q[r++].y = t.y;
}

node front() {
    return q[f];
}

void pop() {
    f++;
}

bool empty() {
    return f == r;
}

int size() {
    return r - f;
}

bool check(int x, int y) {  
    // 越界检查,判断坐标(x, y)是否在合法范围内
    return x >= 1 && y >= 1 && x <= n && y <= n;
}

void bfs(int x, int y) {
    node cur = { x,y };
    push(cur); // 将起点入队
    vis[x][y] = true; // 标记起点为已访问
    while (!empty()) {
        node t = front(); // 取队首元素
        pop();  // 队首元素出队 
        if (t.x == n && t.y == n) return; // 到达终点,结束搜索
        for (int i = 0; i < 4; i++) {
            int nx = t.x + dir[i][0]; // 计算新的x坐标
            int ny = t.y + dir[i][1]; // 计算新的y坐标
            if (check(nx, ny) && !vis[nx][ny]) { // 判断新的坐标是否合法且未被访问过
                cout << Map[nx][ny] << " "; // 输出当前节点的值
                node m = { nx, ny };
                push(m); // 将新的节点入队
                vis[nx][ny] = true; // 标记新的节点为已访问
            }
        }
    }
}

int main() {
    cin >> n; // 输入网格大小
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> Map[i][j]; // 输入每个网格的值
        }
    }
    cout << Map[1][1] << " "; // 输出起点的值
    bfs(1, 1); // 从起点开始进行广度优先搜索
    return 0;
}
View Code

 

代码执行流程

 

 

 本节课作业讲解分析

链接:https://pan.baidu.com/s/1rxmQTgF4PVUQSXwdTdARAQ?pwd=i43w
提取码:i43w