zoukankan      html  css  js  c++  java
  • 方向数组及其应用

    应用场景

    在迷宫、棋盘等问题中,经常需要使用方向数组。

    一般的“寻路”类问题都可以使用方向数组来编程求解。

    示例

    #include <iostream>
    using namespace std;
    
    int dirx[4] = {-1, 0 , 1, 0}; //x direct
    int diry[4] = {0 , 1, 0, -1}; //y direct
    
    int main() {
        int a, b;
        cin >> a >> b;
        for (int i = 0; i < 4; i++) {
            int x = a + dirx[i];
            int y = b + diry[i];
            cout << x << " " << y << endl;
        }
        return 0;    
    }

    【例题】简易迷宫

    输入:

    6 6
    ....##
    ..#.##
    ..#S##
    .T#...
    .##...
    ......

    输出:7

    代码实现(C++)

    #include <iostream>
    #include <queue>
    using namespace std;
    
    struct node {
        int x, y, step;
    };
    
    int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; //x direct
    int n, m, sx, sy;
    char mmap[105][105];
    
    int main() {
        cin >> n >> m;
        for (int i = 1; i <= n; i++) {
            for (int  j = 1; j <= m; j++) {
                cin >> mmap[i][j];
                if (mmap[i][j] == 'S') {
                    sx = i, sy =j;
                }
            }
        }
        queue<node> que;
        que.push((node){sx, sy, 0});
        while (!que.empty()) {
            node temp = que.front();
            que.pop();
            for (int i = 0; i < 4; i++) {
                int x = temp.x + dir[i][0];
                int y = temp.y + dir[i][1];
                if (mmap[x][y] == 'T') {
                    cout << temp.step + 1 << endl;
                    return 0;
                }
                if (mmap[x][y] == '.') {
                    que.push((node){x, y ,temp.step + 1}):
                    mmap[x][y] = 0;
                }     
            }
        }
        cout << -1 << endl;
        return 0;    
    }
    Min是清明的茗
  • 相关阅读:
    Devexpress treeList
    sql rowversion
    2015年8月9日 开始 devsxpress 学习
    定时执行任务
    Dexpress 中 grid的使用
    新版 itextsharp pdf code
    jquery ui 中的插件开发
    Centos7下git服务器及gogs部署
    JAVA(TOMCAT)远程调试
    分布式文件系统笔记(慢慢补充)
  • 原文地址:https://www.cnblogs.com/MinPage/p/14053685.html
Copyright © 2011-2022 走看看