c++迷宮問題最短路徑


// newcoder_xiaohongshu_1.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//

#include "pch.h"
#include <iostream>
#include <queue>
#include <map>


using namespace std;

/*
pair<int, int > p = make_pair(1, 2);
pair<int, int> p(1, 2);
p= new pair<int,int>(1,2)
*/
int dx[4] =  {0,1,0,-1};
int dy[4]=   {1,0,-1,0};

//迷宮地圖,1代表牆壁,0代表通路
int N = 10;
int mat[10][10] = { {1,1,1,1,1,1,1,1,1,1},
    {1,0,0,1,0,0,0,1,0,1},
    {1,0,0,1,0,0,0,1,0,1},
    {1,0,0,0,0,1,1,0,0,1},
    {1,0,1,1,1,0,0,0,0,1},
    {1,0,0,0,1,0,0,0,0,1},
    {1,0,1,0,0,0,1,0,0,1},
    {1,0,1,1,1,0,1,1,0,1},
    {1,1,0,0,0,0,0,0,0,1},
    {1,1,1,1,1,1,1,1,1,1}
};

class Dot {
public:
    int x;
    int y;
    Dot(int x,int y):x(x),y(y){}
};

class WideBlock:public Dot
{
public:
    WideBlock *parent;
    WideBlock(int x,int y,WideBlock* p):Dot(x,y),parent(p){}

    
};

void print(WideBlock *p)//遞歸順序輸出
{
    if (!p->parent)
    
    {
        cout << "\n(" << p->x << "," << p->y << ")" << ";";
    }
    else
    {
        print(p->parent);
        cout << "(" << p->x << "," << p->y << ")" << ";";
    }
}

int main()
{




    WideBlock *s=new WideBlock(1, 1, NULL), *end=new WideBlock(8, 8, NULL);
    queue<WideBlock*> q;
    mat[1][1] = 1;
    q.push(s);
    while (!q.empty())
    {
        WideBlock* cur = q.front();
        q.pop();
        int x = cur->x;
        int y = cur->y;
        if (x == end->x && y == end->y)
        {
            end = cur;
            break;
        }
        if (y + dy[0] < N && mat[x][y + dy[0]] == 0)
        {
            q.push(new WideBlock(x, y + dy[0],cur));
            mat[x][y + dy[0]] = 1;

        }
        if (x + dx[1] < N && mat[x+dx[1]][y] == 0)
        {
            q.push(new WideBlock(x+dx[1], y,cur));
            mat[x+dx[1]][y] = 1;

        }
        if (y + dy[2] > -1  && mat[x][y + dy[2]] == 0)
        {
            q.push(new WideBlock(x, y + dy[2],cur));
            mat[x][y + dy[2]] = 1;

        }
        if (x + dx[3] >-1  && mat[x+dx[3]][y] == 0)
        {
            q.push(new WideBlock(x+dx[3], y,cur));
            mat[x+dx[3]][y] = 1;

        }

        

    }

    WideBlock *tmp = end;
    while (tmp)
    {
        
        
        cout << "(" << tmp->x << "," << tmp->y << ")" << ";";
        tmp = tmp->parent;
    }
    tmp = end;
    print(tmp);

    std::cout << "Hello World!\n";
    return 0;
}

// 運行程序: Ctrl + F5 或調試 >“開始執行(不調試)”菜單
// 調試程序: F5 或調試 >“開始調試”菜單

// 入門提示:
//   1. 使用解決方案資源管理器窗口添加/管理文件
//   2. 使用團隊資源管理器窗口連接到源代碼管理
//   3. 使用輸出窗口查看生成輸出和其他消息
//   4. 使用錯誤列表窗口查看錯誤
//   5. 轉到“項目”>“添加新項”以創建新的代碼文件,或轉到“項目”>“添加現有項”以將現有代碼文件添加到項目
//   6. 將來,若要再次打開此項目,請轉到“文件”>“打開”>“項目”並選擇 .sln 文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM