dijkstra算法Java实现,没有使用库

时间:2014-03-16 17:39:54

标签: dijkstra

在不使用Comparator接口的情况下在Java中实现Dijkstra。

2 个答案:

答案 0 :(得分:1)

首先,您可以在此处阅读算法Pseudocode:http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

这里结束是一个很好的工作启动与比较器..但你必须创建节点,图形等类。 如果比较器是你的问题,那就创建你自己的! ;)

static class distance_Comparator implements Comparator<node>
{

public int compare(node x, node y)
{
    if(x.getDistance()<y.getDistance())
    {
        return -1;
    }
    else if(x.getDistance()>y.getDistance())
    {
        return 1;
    }
    return 0;
}

}

这里是Dijkstra

public static void Dijkstra(graph newgraph)
{

System.out.println("--------------------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------------------");
System.out.println("Running Dijkstra . . . .");
System.out.println("--------------------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------------------");
int sum_average_path=0,average_path=0,numberof_paths=0;
long time_a=System.nanoTime();
//[newgraph.getNum_nodes()]; // shortest known distance from "vertex"
//HashMap visited=new HashMap<>();//[newgraph.getNum_nodes()]; // all false initially
//[newgraph.getNum_nodes()]; // preceeding node in path

distance_Comparator comparator=new distance_Comparator();
PriorityQueue<node> queue = new PriorityQueue<node>((int) newgraph.getNumber_of_nodes(),comparator);


 ///////// find max shortest path : diameter of graph ////////////////
    double  diameter=-1.0;

int s=0,i=0;
double alt=0;

HashMap map;



///////////find all nodes of graph/////////////////
 map=newgraph.getAll_graph_nodes();

for (Object key : map.keySet()) 
{ 
    i++;
   // System.out.println("source node: "+key);

        ///////////////////Initializations////////////////////////////
    /////////////////////////////////////////////////////////////
    HashMap  distance=new HashMap<>(16,0.6f);
    HashMap previous=new HashMap<>(16,0.6f);



    node tmpnode=(node)map.get(key);


    for (Object key_other : map.keySet()) 
    { 
        node x_tmpnode=(node)map.get(key_other);
        distance.put(key_other, Double.POSITIVE_INFINITY);
        x_tmpnode.setDistance(Double.POSITIVE_INFINITY);
        x_tmpnode.setVisited(false);
    }

    tmpnode.setDistance_table(distance);
    tmpnode.setPrevious_table(previous);     
/////////////////////////////////////end  of init//////////////////////////////



    tmpnode.setDistance((double)(0));
    queue.offer(tmpnode); //add tmp node to PriorityQueue
    distance.put(key,(double)(0));

    Stack sta=new Stack();

    while(queue.isEmpty()==false)
    {
        Stack stack_prev=new Stack();

        node queue_tmpnode=queue.poll(); //min_node(distance,map);////vertex in Q with smallest distance in dist[] and has not been visited;  
        queue_tmpnode.setVisited(true);

/*        if(queue_tmpnode.getPrevious_table()!=null)
        {
               // System.out.println("pre: "+prev);
                Stack tmp=(Stack)tmpnode.getPrevious_table().get(queue_tmpnode.getName());
                while(tmp.empty()==false)
                {
                    sta.add(queue_tmpnode.getName());
                    //System.out.println("pop: "+tmp.pop().toString());
                    queue_tmpnode=

                }
        }*/


        HashMap queue_tmpnodemap=(HashMap)queue_tmpnode.getMap();



        if(queue_tmpnodemap!=null)
        {
            //////////////find all Neighbours of node queue_tmpnode////////////////////       
            for (Object v : queue_tmpnodemap.keySet()) 
            {      

               // System.out.println(" v: "+ v.toString());
                node tmpnode_neighbors=(node)map.get(v);


                alt=(double)(queue_tmpnode.getDistance()) ;
                edge tmp_edge= (edge) (queue_tmpnodemap.get(v));  // dist_between(u, v);  --accumulate shortest dist from source

                alt+= tmp_edge.getWeight();

                if ( (alt < tmpnode_neighbors.getDistance()))
                {


                    tmpnode_neighbors.setDistance(alt);                        // keep the shortest dist from src to v
                    distance.put(v, alt);

                    /*
                    stack_prev.add(tmpnode_neighbors.getName());
                    HashMap pre_map=new HashMap();
                    pre_map.put(queue_tmpnode.getName(), stack_prev);
                    previous.put(tmpnode_neighbors.getName(), pre_map);

                    //System.out.println("prev stack: "+stack_prev.size());
                    tmpnode.setPrevious_table(previous);
                    * */

                    if((tmpnode_neighbors.isVisited()==false))
                        queue.add(tmpnode_neighbors);                   // Add unvisited v into the Q to be processed

                }
            }
        }
    }



    HashMap tmp_d=null;
    tmp_d=new HashMap();

        for(Object x: distance.keySet())
        {

            if(Double.parseDouble(distance.get(x).toString()) <  Double.POSITIVE_INFINITY && Double.parseDouble(distance.get(x).toString())!=0)
            {
                //System.out.println("U: "+key+"-> V:"+x+" value: "+t_tmpnode.getDistance_table().get(x));

                tmp_d.put(x, distance.get(x));

            }

        }

  //      System.out.println("V:"+i+" size:"+tmp_d.size()+" capacity:");
        distance.clear();
        tmpnode.setDistance_table(tmp_d);

}



System.out.println("---------------Dijkstra algorithm-------------");
for (Object key : map.keySet()) 
{
    node tmpnode=(node)map.get(key);
   // System.out.println("distance of: "+key.toString()+" , is: ");
     //System.out.print("U: "+key);
    if(tmpnode.getDistance_table()!= null)
    {
        //System.out.println(" dipla monopatia: "+(tmpnode.getShortest_paths_number()-tmpnode.getDistance_table().size()));
        for(Object x: tmpnode.getDistance_table().keySet())
        {
            //if(Double.parseDouble(tmpnode.getDistance_table().get(x).toString()) <  Double.POSITIVE_INFINITY && Double.parseDouble(tmpnode.getDistance_table().get(x).toString())!=0)
                 //System.out.println("U: "+key+"-> V:"+x+" value: "+tmpnode.getDistance_table().get(x));
            if(diameter < (double)tmpnode.getDistance_table().get(x))
                {
                    diameter= (double)tmpnode.getDistance_table().get(x);
                }

                sum_average_path+=(double)tmpnode.getDistance_table().get(x);
                numberof_paths++;


        }
    }
    System.out.println("\n--------------------------------------------");
    for(Object prev: tmpnode.getPrevious_table().keySet())
    {
        System.out.print("node: "+tmpnode.getName()+" path: ");


        HashMap map_prev=(HashMap)tmpnode.getPrevious_table().get(prev);

        for(Object prev_path: map_prev.keySet())
        {
                 System.out.println("V: "+prev+" -> "+prev_path+"");
                Stack tmp=(Stack) map_prev.get(prev_path);
                System.out.println("stacksize: "+tmp.size());
                while(tmp.empty()==false)
                {
                    System.out.println("pop: "+tmp.pop().toString());

                }
        }

    }

}
newgraph.setDiameter(diameter);
System.out.println("Graph diameter is: "+newgraph.getDiameter());
System.out.println("average path lenght: "+((double)((double)sum_average_path/(double)numberof_paths)));
long time_b=System.nanoTime();
System.out.println("Dijkstra time: "+(time_b-time_a)+" time in seconds: "+(double)((time_b-time_a)/1000000000.0));
}

class:node.java

import java.util.HashMap;

public class node {
private int name;
private HashMap map;
private double pagerank_old;
private double pagerank_new;
private double point_to_me;
private HashMap point_to_me_table;
private double point_to_other;
private HashMap betweenness;
private double betweenness_ofvertex;
private int num_nodes;
private double cluster_coefficient;
private int index;
private int lowlink;

private int shortest_paths_number;

private double distance;
private boolean visited;

private int hub_score;
private int auth_score;

private HashMap distance_table;
private HashMap previous_table;
//private edge edge;

public node(int name,HashMap map)
{
    this.name=name;
    this.map=map;

}
public node(int name)
{
    this.name=name;  
}

/**
 * @return the name
 */
public int getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(int name) {
    this.name = name;
}

/**
 * @return the map
 */
public HashMap getMap() {
    return map;
}

/**
 * @param map the map to set
 */
public void setMap(HashMap map) {
    this.map = map;
}



/**
 * @return the pagerank_old
 */
public double getPagerank_old() {
    return pagerank_old;
}

/**
 * @param pagerank_old the pagerank_old to set
 */
public void setPagerank_old(double pagerank_old) {
    this.pagerank_old = pagerank_old;
}

/**
 * @return the pagerank_new
 */
public double getPagerank_new() {
    return pagerank_new;
}

/**
 * @param pagerank_new the pagerank_new to set
 */
public void setPagerank_new(double pagerank_new) {
    this.pagerank_new = pagerank_new;
}

/**
 * @return the pont_to_me
 */
public double getPoint_to_me() {
    return point_to_me;
}

/**
 * @param pont_to_me the pont_to_me to set
 */
public void setPoint_to_me(double pont_to_me) {
    this.point_to_me = pont_to_me;
}

/**
 * @return the point_to_other
 */
public double getPoint_to_other() {
    return point_to_other;
}

/**
 * @param point_to_other the point_to_other to set
 */
public void setPoint_to_other(double point_to_other) {
    this.point_to_other = point_to_other;
}

/**
 * @return the distance
 */
public double getDistance() {
    return distance;
}

/**
 * @param distance the distance to set
 */
public void setDistance(double distance) {
    this.distance = distance;
}

/**
 * @return the visited
 */
public boolean isVisited() {
    return visited;
}

/**
 * @param visited the visited to set
 */
public void setVisited(boolean visited) {
    this.visited = visited;
}

/**
 * @return the distance_table
 */
public HashMap getDistance_table() {
    return distance_table;
}

/**
 * @param distance_table the distance_table to set
 */
public void setDistance_table(HashMap distance_table) {
    this.distance_table = distance_table;
}

/**
 * @return the previous_table
 */
public HashMap getPrevious_table() {
    return previous_table;
}

/**
 * @param previous_table the previous_table to set
 */
public void setPrevious_table(HashMap previous_table) {
    this.previous_table = previous_table;
}

public int getHub_score()
{
    return hub_score;
}

public void setHub_score(int sc)
{
    this.hub_score=sc;
}

public int getAuth_score()
{
    return auth_score;
}

public void setAuth_score(int sc)
{
    this.auth_score=sc;
}

/**
 * @return the point_to_me_table
 */
public HashMap getPoint_to_me_table() {
    return point_to_me_table;
}

/**
 * @param point_to_me_table the point_to_me_table to set
 */
public void setPoint_to_me_table(HashMap point_to_me_table) {
    this.point_to_me_table = point_to_me_table;
}

/**
 * @return the betweenness
 */
public HashMap getBetweenness() {
    return betweenness;
}

/**
 * @param betweenness the betweenness to set
 */
public void setBetweenness(HashMap betweenness) {
    this.betweenness = betweenness;
}

/**
 * @return the cluster_coefficient
 */
public double getCluster_coefficient() {
    return cluster_coefficient;
}

/**
 * @param cluster_coefficient the cluster_coefficient to set
 */
public void setCluster_coefficient(double cluster_coefficient) {
    this.cluster_coefficient = cluster_coefficient;
}

/**
 * @return the betweenness_ofvertex
 */
public double getBetweenness_ofvertex() {
    return betweenness_ofvertex;
}

/**
 * @param betweenness_ofvertex the betweenness_ofvertex to set
 */
public void setBetweenness_ofvertex(double betweenness_ofvertex) {
    this.betweenness_ofvertex = betweenness_ofvertex;
}

/**
 * @return the shortest_paths_number
 */
public int getShortest_paths_number() {
    return shortest_paths_number;
}

/**
 * @param shortest_paths_number the shortest_paths_number to set
 */
public void setShortest_paths_number(int shortest_paths_number) {
    this.shortest_paths_number = shortest_paths_number;
}

/**
 * @return the num_nodes
 */
public int getNum_nodes() {
    return num_nodes;
}

/**
 * @param num_nodes the num_nodes to set
 */
public void setNum_nodes(int num_nodes) {
    this.num_nodes = num_nodes;
}

/**
 * @return the index
 */
public int getIndex() {
    return index;
}

/**
 * @param index the index to set
 */
public void setIndex(int index) {
    this.index = index;
}

/**
 * @return the lowlink
 */
public int getLowlink() {
    return lowlink;
}

/**
 * @param lowlink the lowlink to set
 */
public void setLowlink(int lowlink) {
    this.lowlink = lowlink;
}

}

class:edge

public class edge {
private int a;
private int b;
private double weight;
//private double betweenness;

public edge(int start,int end,double weight){
    this.a=start;
    this.b=end;  
    this.weight=weight;
}

/**
 * @return the a
 */
public int getA() {
    return a;
}

/**
 * @param a the a to set
 */
public void setA(int a) {
    this.a = a;
}

/**
 * @return the b
 */
public int getB() {
    return b;
}

/**
 * @param b the b to set
 */
public void setB(int b) {
    this.b = b;
}

/**
 * @return the weight
 */
public double getWeight() {
    return weight;
}

/**
 * @param weight the weight to set
 */
public void setWeight(double weight) {
    this.weight = weight;
}

}

class:graph

import java.util.HashMap;
import java.util.Stack;


public class graph {

private HashMap all_graph_nodes;
private double number_of_nodes;
private double number_of_edges;
private double diameter;
private double average_degre;
private double density;
private int nodeindex;
private Stack tarjanStack;


public graph(HashMap map,double n_nodes,double m_edges)
{
    this.all_graph_nodes=map;
    this.number_of_nodes=n_nodes;
    this.number_of_edges=m_edges;


}
/**
 * @return the all_graph_nodes
 */
public HashMap getAll_graph_nodes() {
    return all_graph_nodes;
}

/**
 * @param all_graph_nodes the all_graph_nodes to set
 */
public void setAll_graph_nodes(HashMap all_graph_nodes) {
    this.all_graph_nodes = all_graph_nodes;
}

/**
 * @return the number_of_nodes
 */
public double getNumber_of_nodes() {
    return number_of_nodes;
}

/**
 * @param number_of_nodes the number_of_nodes to set
 */
public void setNumber_of_nodes(double number_of_nodes) {
    this.number_of_nodes = number_of_nodes;
}

/**
 * @return the number_of_edges
 */
public double getNumber_of_edges() {
    return number_of_edges;
}

/**
 * @param number_of_edges the number_of_edges to set
 */
public void setNumber_of_edges(double number_of_edges) {
    this.number_of_edges = number_of_edges;
}

/**
 * @return the diameter
 */
public double getDiameter() {
    return diameter;
}

/**
 * @param diameter the diameter to set
 */
public void setDiameter(double diameter) {
    this.diameter = diameter;
}

/**
 * @return the average_degre
 */
public double getAverage_degre() {
    return average_degre;
}

/**
 * @param average_degre the average_degre to set
 */
public void setAverage_degre(double average_degre) {
    this.average_degre = average_degre;
}

/**
 * @return the density
 */
public double getDensity() {
    return density;
}

/**
 * @param density the density to set
 */
public void setDensity(double density) {
    this.density = density;
}

/**
 * @return the nodeindex
 */
public int getNodeindex() {
    return nodeindex;
}

/**
 * @param nodeindex the nodeindex to set
 */
public void setNodeindex(int nodeindex) {
    this.nodeindex = nodeindex;
}

/**
 * @return the tarjanStack
 */
public Stack getTarjanStack() {
    return tarjanStack;
}

/**
 * @param tarjanStack the tarjanStack to set
 */
public void setTarjanStack(Stack tarjanStack) {
    this.tarjanStack = tarjanStack;
}

}

答案 1 :(得分:0)

你可以在下面的链接上找到你如何做到这一点: http://en.literateprograms.org/Dijkstra%27s_algorithm_%28Java%29