首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Dijkstra邻接表

Dijkstra邻接表
EN

Stack Overflow用户
提问于 2016-05-13 22:51:49
回答 1查看 1.9K关注 0票数 2

我遇到了将Dijkstras算法的伪码转换为实际代码的问题。给出和邻接列表,如“位置-相邻位置-距离位置”,例如一个节点: AAA AAC 180 AAD 242 AAH 40。我的任务是读取按描述的邻接列表组织的文件,并计算从一个节点到另一个节点的最短路径。这是Dijkstra伪码:

代码语言:javascript
复制
    void dijkstra( Vertex s )
    {
        for each Vertex v
        {
          v.dist = INFINITY;
          v.known = false;
        }
      s.dist = 0;
        while( there is an unknown distance vertex )
         {
          Vertex v = smallest unknown distance vertex;
          v.known = true;

         for each Vertex w adjacent to v
          if( !w.known )
           {
           DistType cvw = cost of edge from v to w;
           if( v.dist + cvw < w.dist )
             {
    // Update w
           decrease( w.dist to v.dist + cvw );
           w.path = v;
             }
            }
           }
    }

对于“v附近的每个顶点w”这一行,我遇到了最大的麻烦,这里是我的非工作代码:

代码语言:javascript
复制
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Dijkstra {

    public static boolean isInteger(String s) {
        return isInteger(s, 10);
    }

    public static boolean isInteger(String s, int radix) {
        if (s.isEmpty())
            return false;
        for (int i = 0; i < s.length(); i++) {
            if (i == 0 && s.charAt(i) == '-') {
                if (s.length() == 1)
                    return false;
                else
                    continue;
            }
            if (Character.digit(s.charAt(i), radix) < 0)
                return false;
        }
        return true;
    }

    public static void dijkstra(Vertex[] a, Vertex s, int lineCount) {
        int i = 0;
        while (i < (lineCount)) // each Vertex v
        {
            a[i].dist = Integer.MAX_VALUE;
            a[i].known = false;
            i++;
        }

        s.dist = 0;
        int min = Integer.MAX_VALUE; //

        while (!(a[0].known == true && a[1].known == true && a[2].known == true && a[3].known == true
                && a[4].known == true && a[5].known == true && a[6].known == true && a[7].known == true
                && a[8].known == true && a[9].known == true && a[10].known == true && a[11].known == true
                && a[12].known == true)) {
            System.out.println("here");
            for (int b = 0; b < lineCount; b++) {

                if (a[b].dist < min && a[b].known == false) {
                    min = a[b].dist;
                }
            }
            int c = 0;
            while (c < lineCount) {

                if (a[c].dist == min && a[c].known == false) {
                    break;
                }
                c++;
            }
            System.out.println(min);

            a[c].known = true;
            int adjSize = a[c].adj.size();

            int current = 0;

            System.out.println(adjSize);

            while (current < adjSize - 1) {

                String currentAdjacent = (String) a[c].adj.get(current);
                int p = 0;

                while (p < lineCount) {
                    if (a[p].name.equals(currentAdjacent)) {

                        if (!a[p].known) {
                            String cvwString = (String) a[c].distance.get(current);
                            int cvw = Integer.parseInt(cvwString);
                            System.out.println(" This is cvw" + cvw);
                            System.out.println("Here2");

                            if (a[c].dist + cvw < a[p].dist) {
                                a[p].dist = a[c].dist + cvw;
                                a[p].path = a[c];
                            }
                        }
                    }
                    p++;
                }
                current++;
            }
        }
    }

    public static class Vertex {
        public List adj; // Adjacency list
        public List distance;
        public boolean known;
        public int dist; // DistType is probably int
        public Vertex path;
        public String name;

        // Other fields and methods as needed
    }

    public static void printPath(Vertex v) {
        if (v.path != null) {
            printPath(v.path);
            System.out.print(" to ");
        }
        System.out.print(v);
    }

    public static void main(String[] args) throws IOException {

        int lineCounter = 0;

        BufferedReader br = new BufferedReader(new FileReader("airport.txt"));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {

                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();

                lineCounter = lineCounter + 1;
            }

            Vertex[] arr = new Vertex[lineCounter];
            for (int i = 0; i < lineCounter; i++) {
                arr[i] = new Vertex();
                arr[i].adj = new LinkedList<String>();
                arr[i].distance = new LinkedList<Integer>();
            }
            ;

            //
            int arrayCounter = 0;
            String everything = sb.toString();
            String[] lines = everything.split("\\s*\\r?\\n\\s*");

            for (String line1 : lines) {
                arr[arrayCounter] = new Vertex();

                arr[arrayCounter].adj = new LinkedList<String>();
                arr[arrayCounter].distance = new LinkedList<Integer>();
                String[] result = line1.split("\\s+");

                for (int x = 0; x < result.length; x++) {
                    if (x == 0) {
                        arr[arrayCounter].name = result[0];
                        continue;
                    } else if (isInteger(result[x])) {
                        arr[arrayCounter].distance.add(result[x]);
                        continue;
                    } else {
                        arr[arrayCounter].adj.add(result[x]);
                        continue;
                    }
                }

                arrayCounter++;
            }

            for (int i = 0; i < 12; i++) {
                System.out.println(arr[i].name);
            }
            System.out.println(lineCounter);
            dijkstra(arr, arr[3], lineCounter - 1);
            printPath(arr[11]);

        } finally {
            br.close();
        }
    }
}

使用我的顶点类,我首先使用一系列while循环,遍历存储在链表中的邻接字符串,同时比较哪个顶点等效于邻接列表字符串。是否有更好的方法使用我的顶点类为“v相邻的每个顶点w”编码?为我可能犯下的乱七八糟的代码和其他风格的罪过道歉。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-14 01:13:31

要解决这个问题,您需要一堆存储在HashMap中的“节点”对象,键控在源位置上。

在节点中,您需要一组对相邻" node“对象(或至少是它们的”键“)的引用,以便可以针对它编写逻辑。“节点”还需要知道它的位置和到每个“相邻”节点的距离。想想看,伦登地下地铁地图-每个站至少连接到另一个站。通常是两个或更多。因此,相邻的节点到地铁站是下一站,你可以立即从该站到达。

一旦数据结构就位,就可以使用递归例程迭代每个节点。然后,它应该遍历每个子节点(也称为相邻节点),并通过将数据存储在HashMap中并使用当前累积距离来跟踪从初始(源)节点到当前节点的距离,同时递归(或“遍历”图形)。当递归时,此跟踪信息应该是方法签名的一部分。您还需要跟踪递归时所走的当前路径,以避免循环循环(这最终会导致StackOverflowError)。您可以通过使用HashSet来实现这一点。此集合应跟踪源节点和当前节点的位置作为入口键。如果您在递归过程中看到了这个存在,那么您已经看到它了,所以不要继续处理。

我不会为您编写解决方案的代码,因为我怀疑您在理解答案时会提出更具体的问题,这些问题很可能是在其他地方回答的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37220459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档