在圖中尋找最短路徑-----深度優先算法C++實現


求從圖中的任意一點(起點)到另一點(終點)的最短路徑,最短距離;

圖中有數字的點表示為圖中的不同海拔的高地,不能通過;沒有數字的點表示海拔為0,為平地可以通過;

這個是典型的求圖中兩點的最短路徑;本例,用深度優先算法來實現;

在每一個點都有四個方向(有的點的有些方向不能通過),所以在每一個點處要處理四種方向的情況;

深度優先算法函數怎么寫?

也就是寫遞歸函數。。。但是遞歸函數腫么寫???

第一:判斷初始態,從起點出發,剛開始步數為0;dfs(start_x, start_y, 0);

第二:從起點出發,要做什么事情?嘗試四個方向的走法。

           在每個方向上要什么?先判斷這個點是否到達邊界,再判斷這個點是否走過並且是否是高地;如果不是高地也沒有走過,則再從該點出發,做和之前的點一樣的事情;

dfs(tx, ty, step+1);

第二:判斷終止條件,到達終點,判斷當前步數;返回;

/*************************************************************************
	> File Name: search_min_step.cpp
	> Author: 
	> Mail: 
	> Created Time: 2015年11月13日 星期五 21時49分41秒
 ************************************************************************/

#include<iostream>

using namespace std;

const int MAX_X = 50;
const int MAX_Y = 50;
int min_step = 10000;
int my_x, my_y;
int map[MAX_X][MAX_Y];
int book[MAX_X][MAX_Y];
int start_x, start_y;
int dest_x, dest_y;

void dfs(int x, int y, int step)
{
    /*up, right, down, left*/
    int next[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
    int tx, ty;

    if (x == dest_x && y == dest_y){
        if (step < min_step)
            min_step = step;
        return;
    }

    for (int i = 0; i < 4; i++){
        tx = x + next[i][0];
        ty = y + next[i][1];
        if (tx > my_x || ty > my_y || tx < 0 || ty < 0)
            continue;

        if (map[tx][ty] == 0 && book[tx][ty] == 0){
            book[tx][ty] = 1;
            dfs(tx, ty, step+1);
            book[tx][ty] = 0;
        }
    }

}
void input_map_info()
{
    cout << "input the max x:";
    cin >> my_x;
    cout << "input the max y:";
    cin >> my_y;

    cout << "input the map information:\n";
    for (int i = 1; i <= my_x; i++){
        for (int j = 1; j <= my_y; j++){
            cin >> map[i][j];
        }
    }
}

int main()
{
    input_map_info();

    cout << "input the source location:";
    cin >> start_x >> start_y;
    cout << "input the destat location:";
    cin >> dest_x >> dest_y;

    book[start_x][start_y] = 1;
    dfs(start_x, start_y, 0);
    
    cout << "min_step = " << min_step << endl;

    return 0;
}


免責聲明!

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



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