布线问题--队列式分支界限法

#include <iostream>
#include <queue>
#include <algorithm>
#include <utility>
#include <stack>
using namespace std;

typedef pair<int, int> posi;
queue<posi> q;
const int n = 100;
int graph[n+2][n+2] = {0};
posi start;
posi end;
int best_path = 0;
void initParament()
{

}

void findPath()
{
        if(start.first == end.first && start.second==end.second){
                return;
        }

        for(int i=0; i<=n; i++){
                graph[0][i] = 1;
                graph[n+1][i] = 1;
                graph[i][0] = 1;
                graph[i][n+1] = 1;
        }

        posi offset[5];
        offset[1].first = 1; offset[1].second = 0;
        offset[2].first = 0; offset[1].second = -1;
        offset[1].first = -1; offset[1].second = 0;
        offset[1].first = 0; offset[1].second = 1;

        posi current = start;
        graph[current.first][current.second] = 2;
        while( true ){
                posi here;
                for(int i=1; i<=4; i++){
                        here.first = current.first+offset[i].first;
                        here.second = current.second+offset[i].second;

                        if(graph[here.first][here.second] == 0){
                                q.push(here);
                                graph[here.first][here.second] = graph[current.first][current.second] + 1;

                                if(here.first == end.first && here.second == end.second){
                                        best_path = graph[here.first][here.second];
                                        break;
                                }
                        }
                }

                if(here.first==end.first && here.second==end.second){
                        break;
                }

                if( q.empty() ){
                        break;
                }

                current = q.front();
                q.pop();
        }

        stack<posi> path;
        path.push(end);
        current = end;
        for(int i=best_path; i>2; i–){
                posi here;
                for(int j=1; j<=4; j++){
                        here.first = end.first+offset[j].first;
                        here.second = end.second+offset[j].second;

                        if(graph[here.first][here.second] == i-1){
                                path.push(here);
                                break;
                        }
                }
                current = here;
        }
        path.push(start);

        while( !path.empty() ){
                current = path.top();
                cout << current.first << “,” << current.second << endl;
                path.pop();
        }
}

int main()
{
        initParament();

        findPath();

        return 0;
}

    原文作者:分支限界法
    原文地址: https://blog.csdn.net/hongshundi/article/details/4672661
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞