Using Java to implement Dijkstra output to specify the shortest path to the end point __java

Source: Internet
Author: User
Tags gety prev

Recently participated in a competition in the company, which involves a problem that can be simplified as a description: a two-dimensional matrix, each point has a weight, you need to find from the specified starting point to the end of the shortest path.

Immediately thought of the Dijkstra algorithm, so again warm up again, here give a Java implementation.

And the output of the shortest path, the online also made a lookup, did not find any standard method, so in the following implementation, I gave a more concise way to think of: using prev[] array for recursive output.

Package Graph.dijsktra;

Import Graph.model.Point;

Import java.util.*;
 /** * Created by MHX on 2017/9/13. * * Public class Dijkstra {private int[][] map;//MAP structure save private int[][] edges;//adjacency Matrix private int[] prev; /precursor node label private boolean[] s; s set to the point in the beginning of the shortest path has been calculated private int[] dist; Dist[i] represents the shortest path from the beginning to the first node, private int pointnum; Number of points private map<integer, point> Indexpointmap; The corresponding relationship of the marking and the point private Map<point, integer> Pointindexmap; The corresponding relation of the point and the label is private int v0; Beginning marking private point startpoint; Beginning private point EndPoint; End of private map<point, point> Pointpointmap; The mapping relationship between savepoint and weights private list<point> allpoints; Save All points private int maxX; The maximum value of the X coordinate is private int maxy;
        The maximum value of the y-coordinate is public Dijkstra (int map[][], point startpoint, point endPoint) {This.maxx = Map.length;
        This.maxy = Map[0].length;
        This.pointnum = MaxX * MAXY;
        This.map = map; This.starTpoint = StartPoint;
        This.endpoint = EndPoint;
        Init ();
    Dijkstra (); /** * Print the shortest path to the specified starting point to the endpoint/public void Printshortestpath () {Printdijkstra ()-Pointindexmap.get (end
    Point)); }/** * Initialize Dijkstra */private void init () {//Initialize all variables edges = new Int[pointnum][point
        Num];
        prev = new Int[pointnum];
        s = new Boolean[pointnum];
        dist = new Int[pointnum];
        Indexpointmap = new hashmap<> ();
        Pointindexmap = new hashmap<> ();
        Pointpointmap = new hashmap<> ();

        allpoints = new arraylist<> ();
        Converts all points in a map two-dimensional array to their own structure int count = 0; for (int x = 0; x < MaxX; ++x) {for (int y = 0; y < Maxy; ++y) {Indexpointmap.put
                T, new Point (x, y));
                Pointindexmap.put (new Point (x, y), count);
                count++;
             Allpoints.add (new Point (x, y));   Pointpointmap.put (new Point (x, y), New Point (X, Y, map[x][y]); }///Initialize adjacency matrix for (int i = 0; i < Pointnum ++i) {for (int j = 0; J < Pointnu M
                ++J) {if (i = = j) {Edges[i][j] = 0;
                else {edges[i][j] = 9999;
            }}///Based on the weights on the map initialize edges, of course, this algorithm is not a separate plus the weight of the starting point point:allpoints { for (point aroundpoint:getaroundpoints) {edges[pointindexmap.get (point)][pointindexmap.get (
            Aroundpoint)] = Aroundpoint.getvalue ();

        } V0 = Pointindexmap.get (startpoint);
            for (int i = 0; i < Pointnum ++i) {dist[i] = Edges[v0][i]; if (dist[i] = = 9999) {//If the shortest path from 0 (the starting point) to the I point is 9999, i.e. unreachable/the precursor node of the I node does not exist prev[
            I] =-1; else {//Initialize the predecessor node of the I node as the starting point, because this timeThe shortest paths are those that are directly connected with the starting point prev[i] = V0;
        }} Dist[v0] = 0;
    S[v0] = true; }/** * Dijkstra core algorithm */private void Dijkstra () {for (int i = 1; i < Pointnum; ++i) {//At this point
            There is a pointNum-1 point in the U set, which needs to be cycled pointNum-1 the second int mindist = 9999;

            int u = v0; for (int j = 1; j < Pointnum; ++j) {//In the U set, find the dot if (!s[j] && dist[j] < mindist) of the shortest starting distance {
                    Not in S set, which is in U set u = j;
                Mindist = Dist[j]; }} S[u] = true; Place this point in the S set for (int j = 1; j < Pointnum ++j) {//is based on the point U, which is currently just placed in the s set from the U set, and loops its reachable point if (!s[
                        J] && Edges[u][j] < 9999 {if (Dist[u] + edges[u][j] < Dist[j]) {
                        DIST[J] = Dist[u] + edges[u][j];
                    PREV[J] = u;
}
                }
            }
        }
    }
    private void Printdijkstra (int endpointindex) {if (Endpointindex = = V0) {System.out.print (index
            Pointmap.get (V0) + ",");
        Return
        } Printdijkstra (Prev[endpointindex]);
    System.out.print (Indexpointmap.get (Endpointindex) + ","); Private list<point> getaroundpoints (point point) {list<point> aroundpoints = new arraylist<
        > ();
        int x = Point.getx ();
        int y = point.gety ();
        Aroundpoints.add (new Point (X-1, y)) (pointpointmap.get);
        Aroundpoints.add (new Point (x, y + 1)) (Pointpointmap.get);
        Aroundpoints.add (new Point (x + 1, y)) (pointpointmap.get);
        Aroundpoints.add (Pointpointmap.get) (New Point (X, y-1)); Aroundpoints.removeall (Collections.singleton (null));
    Remove null points not in the map range return aroundpoints;
                public static void Main (string[] args) {int map[][] = {{1, 2, 2, 2, 2, 2, 2}, {1, 0, 2, 2, 0, 2, 2}, {1, 2, 0, 2, 0, 2, 2}, {1, 2, 2, 0, 2, 0, 2}, {1, 2, 2, 2, 2, 2, 2 }, {1, 1, 1, 1, 1, 1, 1}}; Each point is represented by a weight, without a direction to limit points startpoint = new (0, 3); Point endPoint = new points (5, 6);
        Endpoint Dijkstra Dijkstra = new Dijkstra (map, StartPoint, endPoint);
    Dijkstra.printshortestpath (); }
}

Package Graph.model;
    public class Point {private int x;
    private int y;

    private int value;
        public point (int x, int y) {this.x = x;
    This.y = y;
        public point (int x, int y, int value) {this.x = x;
        This.y = y;
    This.value = value;
    public int GetX () {return x;
    public void SetX (int x) {this.x = x;
    public int GetY () {return y;
    The public void sety (int y) {this.y = y;
    public int GetValue () {return value;
    public void SetValue (int value) {this.value = value;  @Override public String toString () {return "{" + "x=" + x + ", y=" + y
    +
                '}';
        @Override public boolean equals (Object o) {if (this = O) return true;

        if (o = = NULL | | getclass ()!= O.getclass ()) return false;

        Point point = (point) o; if (x!= point.x) return false;
    return y = = Point.y;
        @Override public int hashcode () {Int. result = x;
        result = ~ result + y;
    return result; }
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.