【问题标题】:Creating adjacency list from 2D array of ints从整数的二维数组创建邻接列表
【发布时间】:2021-12-29 09:21:01
【问题描述】:

我在编写算法以查找时遇到了障碍: a) 最短的公交路线和 b) 开关最少的路线。 我需要使用 BFS 来解决它,但是我们没有为每个顶点提供一个邻接列表,所以我很困惑如何从一个 2D 整数数组中制作邻接列表,每个数字代表一个总线停止,每一行都是自己的路线:

So, [1 2 3 4 5] is Route 1, 
    [6 7] is Route 2 etc. 
Also, the first station of each route is the next station 
the bus will reach from the last station of the route, 
so each route goes in circles: 
1 -> 2 -> 3 -> 4 -> 5 -> 1 -> 2 -> ...
 1 2 3 4 5
 6 7
 8 7 4
 2 6

到目前为止,我拥有的是这样的:

public void fillAdjacencyList(int[][] routes){
        for(int i=0; i<routes.length; i++){
            for(int j=0; j<routes[i].length; j++){
                if(this.stop==routes[i][routes[i].length-1]){
                    BusStop temp=new BusStop(routes[i][0]);
                    this.next.add(temp);
                }else{
                    if(routes[i][j]==this.stop){
                        BusStop temp=new BusStop(routes[i][j+1]);
                        this.next.add(temp);
                    }
                }
            }
        }
        this.visited='*';
    }

当我从我需要找到最短公交路线的起点读取起点时,第一个顶点被初始化。每个顶点定义为:

    int stop;
    ArrayList<BusStop> next;
    char visited;
    char created;
    int[] line;

    public BusStop(int st){
        this.stop=st;
        this.created='*';
    }

【问题讨论】:

  • 你能解释一下二维整数数组代表什么吗?

标签: breadth-first-search adjacency-list


【解决方案1】:

下面的 Python 函数完成了这项工作。我用 python 做的,所以它不那么冗长并且(希望)更容易理解

def to_adj(routes):
    adj = { }
    for route in routes:
        for stop in route:
            if stop not in adj:
                adj[stop] = []

        for i in range(len(route)):
            adj[route[i]].append(route[(i+1) % len(route)])

    return adj

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2016-12-27
    • 1970-01-01
    • 2018-05-13
    • 2016-08-24
    • 1970-01-01
    相关资源
    最近更新 更多