zoukankan      html  css  js  c++  java
  • STL应用 queue poj 1915

    queue 队列数据结构
    只支持从队前端弹出元素pop,队尾端插入数据push.不支持下标索引访问。
    类函数比较少
    push()  pop() size() front() empty()

    但是他是BFS  广度优先搜索的基础。

    这里以poj 1915 为例子,演示在BFS中如何使用queue

    poj 1915
    https://vjudge.net/problem/POJ-1915
    题目大意

    输入一个正方形国际棋盘大小,和棋子所在坐标,以及要求走到的终点坐标。要求我们输出移动的最小次数。
    棋子移动类似象棋的马,走日字格子,如图
    

    输入 
    第一行 输入一个数字N 表示测试用例个数
    每个用例包括三行
    1 包括棋盘长度 4<=L<=300
    2 棋子的起始位置 x y
    3 棋子的目标位置 m n
    
    输出
    输出一行一个数字 表示移动的最少次数
    
    Sample Input
    3
    8
    0 0
    7 0
    100
    0 0
    30 50
    10
    1 1
    1 1
    Sample Output
    5
    28
    0
    

    解答
    使用bfs逐步计算棋子可以走到的坐标,找到终点。
    image

    #include <iostream>
    #include <queue>
    
    
    
    using  namespace std;
    
    const int N = 310;
    
    int board[N][N];
    
    //每次移动的xy的增加量
    int addx[8] = { 2,2,1,1,-1,-1,-2,-2 };
    int addy[8] = { 1,-1,2,-2,2,-2,1,-1 };
    
    //记录已经被访问了 避免重复访问
    int vis[N][N];
    
    int n;
    
    struct INFO {
    	int x;
    	int y;
    	int step;
    };
    
    int main()
    {
    	cin >> n;
    	while (n--) {
    		memset(vis, 0, sizeof vis);
    		int width;
    		int startx, starty;
    		int targetx, targety;
    		cin >> width;
    		cin >> startx >> starty;
    		cin >> targetx >> targety;
    		if (startx == targetx && starty == targety) {
    			cout << 0 << endl;
    			continue;
    		}
    
    		queue<struct INFO> q;
    		//队列中存储的信息有三个元素 走到的坐标x 做到的坐标y  使用到的步数
    		struct INFO info; info.x = startx; info.y = starty; info.step = 0;
    		q.push(info);
    		vis[startx][starty] = 1;
    		while (!q.empty()) {
    			int currx = q.front().x;
    			int curry = q.front().y;
    			int currstep = q.front().step;
    			q.pop();
    
    			if (currx == targetx && curry == targety) {
    				//达到终点 
    				cout << currstep << endl;
    				break;
    			}
    
    			//尝试向八个方向移动
    			for (int i = 0; i < 8; i++) {
    				int newx = currx + addx[i];
    				int newy = curry + addy[i];
    
    				//检测新得到的坐标是否合法 是否已经被访问过
    				if (newx >= 0 && newx < width && newy >= 0 && newy < width && vis[newx][newy] == 0) {
    					struct INFO info; info.x = newx; info.y = newy; info.step = currstep +1;
    					q.push(info); vis[newx][newy] = 1;
    				}
    			}
    		}
    	}
    }
    
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    js/css 伪类, 获取伪类样式
    JS 盒子模型
    python坑之input获取字符串
    configpraser模块
    类的特殊成员&反射&异常处理
    面向对象
    员工信息表
    re正则表达式
    PyCharm教程
    递归实现jsonTree
  • 原文地址:https://www.cnblogs.com/itdef/p/15083799.html
Copyright © 2011-2022 走看看