【问题标题】:Build a random Hamiltonian path in a graph在图中构建随机哈密顿路径
【发布时间】:2017-11-12 21:53:53
【问题描述】:

在我的代码中,我在图中找到了哈密顿路径来解决另一个问题。
我现在正在测试我的代码,我想获取一个没有边的通用图并在其中构造一条汉密尔顿路径。在那个图上(现在有形成哈密顿路径的边)我将根据Erdős–Rényi model 添加随机边。 通过这种方式,我可以看到我的代码处理具有不同边数的图形的速度。
我可以处理的有效图表如下所示:

  1. 为矩阵中的每个单元格添加一个顶点。
  2. 如果顶点 u 和 v 在矩阵中相邻,则 可以 连接。
    我的目标是生成一个随机有效图汉密尔顿路径。

问题在于,如果不重复所有可能的路径并找到一个穿过所有顶点的路径,我就找不到一种有效的方法来构建哈密顿路径。

例如:

The matrix:        Possible path:    Not possible:
-------------       
| 1 | 2 | 3 |        1 - 2 - 3         1 - 2 - 3 _
-------------                |                    |
| 4 | 5 | 6 |        4 - 5 - 6         4 - 5 - 6  |
-------------        |                 |          |
| 7 | 8 | 9 |        7 - 8 - 9         7 - 8 - 9_/
-------------       

第二条路径是不可能的,因为 3 和 9 在矩阵中不相邻。
有没有办法在仅给定矩阵的情况下在线性时间内构造一条哈密顿路径?

【问题讨论】:

  • 也许this 会有所帮助
  • 不清楚您的矩阵如何表示图形。
  • 我添加了一些关于我的图表的外观以及如何构建它们的更多细节。 @亨利
  • 我建议删除以“On that graph I would add ...”开头的句子,因为它描述的内容与您要解决的直接问题无关(对吗?),因此是有点混乱。
  • 考虑到您将进一步处理图表,为什么最小生成树不能完成这项工作?

标签: java algorithm graph


【解决方案1】:
package hamiltonian_path;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;



public class Main {

    int[] solution;
    HashMap<Integer, List<Integer>> candidates;

    public static void main(String args[]) {
        Main main = new Main();
        main.solution = new int[10];//stores the solution; index 0 is not used, i will use indexes from 1 to 9
        main.candidates = new HashMap<Integer, List<Integer>>();//for each position (1 to 9) in the solution, stores a list of candidate elements for that position

        List<Integer> oneToNine = new LinkedList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
        /*
         * because no solution can start from matrix elements 2,4,6 or 8, 
         * for the sake of optimization, the above list can be written as
         * Arrays.asList(1,3,5,7,9)
         * the way it is right now is useful to follow the way the program 
         * does the backtracking, when it accidentally starts with either 2,4,6 or 8
         */
        Collections.shuffle(oneToNine);//a random permutation of the list
        main.candidates.put(1, oneToNine);
        main.buildSol(1);

    }

    //backtracking
    public void buildSol(int k)
    {
        if(k==10)
        {
            System.out.print("the solution is ");
            printSolution();
            return;
        }

        List<Integer> candList = candidates.get(k);
        if(candList.isEmpty())
        {
            cleanSolution(k);
            buildSol(k-1); //if no candidates for current step, go one step back
        }
        else
        {
            int firstCandidate = candList.get(0);
            candList.remove(0);
            candidates.put(k, candList);
            solution[k] = firstCandidate;//for the position k in the solution, pick the first element in the candidates list

            List<Integer> neighbors = getNeighbors(solution[k]);
            List<Integer> prevElems = getPreviousElementsInSolution(k);
            candidates.put(k+1, generateCandidates(neighbors, prevElems));//while being at step k, generate candidate elements for step k+1
            //these candidates are the neighbors (in the matrix) of the current element (solution[k]), 
            //which are not already part of the solution at an earlier position

            System.out.println("step "+k);
            System.out.print("partial solution: ");
            printSolution();
            System.out.println();


            buildSol(k+1);//go to next step
        }
    }



    //candidates are those elements which are neighbors, and have not been visited before
    public List<Integer> generateCandidates(List<Integer> neighbors, List<Integer> previousElements) 
    {
        List<Integer> cnd = new ArrayList<Integer>();
        for(int i=0;i<neighbors.size();i++)
            if(!previousElements.contains(neighbors.get(i)))
                cnd.add(neighbors.get(i));

        return cnd;
    }

    //get the set of previous elements in the solution, up to  solution[k]
    public List<Integer> getPreviousElementsInSolution(int step)
    {
        List<Integer> previousElements = new ArrayList<Integer>();
        for(int i=1; i<=step-1;i++)
            previousElements.add(solution[i]);

        return previousElements;
    }

    //get neighbors of the matrix element which corresponds to solution[k]

    public  List<Integer> getNeighbors(int element) {

        List<Integer> neighboursList = new ArrayList<Integer>();

        switch (element) {

            case 1: neighboursList = Arrays.asList(2, 4);
                    break;

            case 2: neighboursList = Arrays.asList(1, 3, 5);
                    break;

            case 3: neighboursList = Arrays.asList(2, 6);
                    break;

            case 4: neighboursList = Arrays.asList(1, 5, 7);
                    break;

            case 5: neighboursList = Arrays.asList(2, 4, 6, 8);
                    break;

            case 6: neighboursList = Arrays.asList(3, 5, 9);
                    break;

            case 7: neighboursList = Arrays.asList(4, 8);
                    break;

            case 8: neighboursList = Arrays.asList(5, 7, 9);
                    break;

            case 9: neighboursList = Arrays.asList(6, 8);
                    break;

            default: neighboursList = new ArrayList<Integer>();
                    break;
        }

        return neighboursList;
    }



    public void printSolution()
    {
        for(int i=1;i<solution.length;i++)
            System.out.print(solution[i]+" ");
    }

    public void cleanSolution(int k)
    {
        for(int i=k;i<solution.length;i++)
            solution[i]=0;
    }
}

【讨论】:

  • 那么如果不重复所有可能的解决方案就没有办法做到这一点?
  • 如果你仔细看,当我找到解决方案的那一刻(测试长度是否为 10),我打印它并调用 return,退出该方法。这段代码根本没有迭代所有可能的解决方案;它迭代大量的解决方案;它试图构建一个解决方案——如果它可以直接构建它——它会;否则,如果它到达死胡同,它会后退一步,尝试另一个分支
  • 如果您查看打印语句,程序后退很多的时刻是它意外以 2,4,6,8 开头的时刻 - 这导致没有解决方案。正如我在 cmets 中所说,为了优化,将 oneToNine 列表修改为 new LinkedList&lt;Integer&gt;(Arrays.asList(1,3,5,7,9)); 。打印语句将反映解决方案的生成更加直接
猜你喜欢
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
相关资源
最近更新 更多