• [BFS] [洛谷] P1443 吗的便利


    一看求最短路径

    即为BFS

    偷懒写DFS无限超时

    #pragma GCC optimize(2)
    #include <cstdio>
    #include <iostream>
    #include <cstdlib>
    #include <cmath>
    #include <cctype>
    #include <string>
    #include <cstring>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <set>
    #include <map>
    #include <ctime>
    #include <vector>
    #include <fstream>
    #include <list>
    #include <iomanip>
    #include <numeric>
    using namespace std;
    typedef long long ll;
    
    const int MAXN = 1e6 + 10;
    
    int arr[410][410];
    
    struct node
    {
        int x, y, step;
    
        node(int xa, int ya, int za)
        {
            x = xa;
            y = ya;
            step = za;
        }   
    };
    
    int movel[4][2] = { {1, -2}, {2, -1}, {2, 1}, {1, 2} };
    
    ll n, m;
    
    queue <node> Q;
    
    void bfs(node a)
    {
        Q.push(a);
    
        while(!Q.empty())
        {
            node b = Q.front();
    
            Q.pop();
    
            if( !(b.x < 1 || b.x > n || b.y < 1 || b.y > m || arr[b.x][b.y] >= 0 ) )
            {
                arr[b.x][b.y] = b.step;
    
                for(int i = 0; i < 4; i++)
                {
                    
                    Q.push(node(b.x + movel[i][0], b.y + movel[i][1], b.step + 1));
    
    
                    Q.push(node(b.x - movel[i][0], b.y - movel[i][1], b.step + 1));
                }
            }
        }
    }
    
    void puts()
    {
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= m; j++)
            {
                cout<<left<<setw(5)<<arr[i][j];
            }
            cout<<endl;
        }
    }
    
    int main()
    {
        ios::sync_with_stdio(false);
    
        cin.tie(0);     cout.tie(0);
    
        cin>>n>>m;
    
        memset(arr, -1, sizeof(arr));
    
        //memset(used, 0, sizeof(arr));
    
        int x, y;
    
        cin>>x>>y;
    
        node in(x, y, 0);
        
        bfs(in);
    
        puts();
    
    
        return 0;
    }
  • 相关阅读:
    intellij idea
    this.getClass().getResource(String) 路径问题
    org.hibernate.AssertionFailure: null id 错误
    Hibernate 映射
    关于idea 在创建maven 骨架较慢问题解决
    常用base.css
    form表单样式
    ul li自适应居中导航
    table-cell实现未知宽高图片,文本水平垂直居中在div
    多行文字水平垂直居中在div
  • 原文地址:https://www.cnblogs.com/zeolim/p/12270479.html
Copyright © 2020-2023  润新知