如何构造图?

时间:2019-05-09 21:33:02

标签: java graph breadth-first-search treenode

我正在从事一个项目,该项目涉及解析数据文件并将其读取为图形。在此图中,我必须找到两个顶点之间的最短距离。实际上,我已经尝试了几天,但似乎无法弄清楚如何绘制此图。

我尝试使用Dijkstra的算法,但是我发现一个简单的BFS会更容易理解,但是我不知道如何首先构造图形。

 import java.util.ArrayList;

 /* 
  * Here we create an undirected graph
 */
public class Graph 
{

    public int [][] adjmatrix; 
    public int vertices;


    public Graph(int vertices) 
    {
        // TODO Auto-generated constructor stub
        adjmatrix = new int[vertices][vertices];            
        this.vertices = vertices;                           


    }

    public void addEdge(String actor, String actor2, String movie)
    {
        if(getVertex(actor) == -1)
        {

        }
    }


    public int[] neighbors(int vertex) 
    {

        ArrayList<Integer> neighbors = new ArrayList<>(); 

        for (int i = 0; i < vertices; i++) {

            if(adjmatrix[vertex][i] == 0)
            {
                neighbors.add(i);
            }
        }

        int size = neighbors.size();

        int[] neighbor = new int[size];

        for(int i = 0; i < size; i++){

            neighbor[i] = neighbors.get(i);
        }
        return neighbor;
    }

    public void makePath(String actor, String actor2)
    {

    }
}

结果是创建一个图形并创建一个查找最短距离的函数。我不需要帮助弄清楚如何找到最短的距离,因为该功能对我来说很简单,但是我首先需要帮助构造图形。

2 个答案:

答案 0 :(得分:0)

假设您有顶点数量(仅计算数量),请使用2D-数组。

int [][] edges = new int[vertices][vertices]; // vertices of map

edges[BeginningVertex][EndingVertex] = Weight or time needed to cross;

答案 1 :(得分:0)

我建议使用以下代码创建图(有向图)并运行BFS算法:

Graph.java

public class Graph {

    private final boolean [][]MAT;

    private final int NODE_NUMBER;

    public Graph(int NODE_NUMBER) {
        this.NODE_NUMBER = NODE_NUMBER;
        this.MAT = new boolean [NODE_NUMBER][NODE_NUMBER];
    }



    public void addEdge(int nodeA , int nodeB){
        this.MAT[nodeA][nodeB] = true;
    }


    public boolean hasEdge(int nodeA, int nodeB){
        return MAT[nodeA][nodeB];
    }


    public final int getNodeSize(){
        return NODE_NUMBER;
    }
}

BfsResult.Java

import java.util.ArrayList;
import java.util.List;


public class BfsResult {

    private final int root;

    private final boolean []visited;

    private final int []distance;

    private final int []parent;


    public BfsResult(int root, boolean[] visited, int[] distance, int[] parent) {
        this.root = root;
        this.visited = visited;
        this.distance = distance;
        this.parent = parent;
    }

    public int getRoot() {
        return root;
    }

    public int getParent(int node){
        return parent[node];
    }

    public int getDistance(int node){
        return distance[node];
    }

    public boolean isAccessible(int node){
        return visited[node];
    }


    public int[] getPath(int node){

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

        int cur = node;
        do{
            path.add( cur );
            cur = parent[cur];

        }while ( cur != -1 );


        int []pathArray = new int[path.size()];

        for(int i = 0 ; i < path.size() ; ++i){
            pathArray[i] = path.get( path.size() - (i + 1) );
        }

        return pathArray;

    }

    public String getPathString(int node) {
        int[] path = getPath( node );

        StringBuilder builder = new StringBuilder(  );

        for ( int i = 0; i < path.length; i++ ) {
            builder.append( path[i] );

            if(i + 1 < path.length){
                builder.append( " -> " );
            }
        }

        return builder.toString();
    }
}

BfsAlgorithm.java

import java.util.LinkedList;
import java.util.Queue;


public class BfsAlgorithm {


    private final Graph graph ;
    private final int root;

    public BfsAlgorithm(Graph graph, int root) {
        this.graph = graph;
        this.root = root;
    }

    public BfsResult run() {

        boolean []visit     = new boolean[graph.getNodeSize()];
        int     []distances = new int    [graph.getNodeSize()];
        int     []parents   = new int    [graph.getNodeSize()];

        Queue<Integer> queue = new LinkedList<>();

        visit[root]     = true;
        distances[root] = 0;
        parents[root]   = -1;

        queue.add( root );

        while( !queue.isEmpty() ){

            int currentNode = queue.poll();

            for(int i = 0 ; i < graph.getNodeSize() ; ++i){

                if( graph.hasEdge( currentNode , i ) && !visit[i] ){

                    visit    [i] = true;
                    distances[i] = distances[currentNode] + 1;
                    parents  [i] = currentNode;

                    queue.add(i);
                }
            }
        }

        return new BfsResult( root, visit, distances, parents );


    }
}

Main.java

public class Main {


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

        //create sample graph with 6 node
        Graph graph = new Graph( 6 );

        //directed edges:
        graph.addEdge( 0 , 1 ); 
        graph.addEdge( 0 , 2 );
        graph.addEdge( 1 , 3 );
        graph.addEdge( 2 , 4 );
        graph.addEdge( 4 , 5 );

        //select root node of bfs
        int root = 0;

        BfsAlgorithm algorithm = new BfsAlgorithm( graph, root );

        BfsResult result = algorithm.run();

        //show result
        for ( int i = 0; i < graph.getNodeSize(); i++ ) {

            if(result.isAccessible( i )){
                System.out.printf("From node %d to %d  is accessible\n" ,result.getRoot() ,i  );
                System.out.printf("Distance between node  %d -> %d  is %d\n" ,result.getRoot() , i , result.getDistance( i ) );
                System.out.printf("Path     between node  %d -> %d  is:\t%s\n" ,result.getRoot() , i , result.getPathString( i ) );
            }else{
                System.out.printf("From node %d to %d  is not accessible!\n" ,result.getRoot() ,i );
            }

            System.out.println("\n ------------------------ \n");
        }



    }


}

我通过根0运行此算法:

enter image description here

结果是:

From node 0 to 0  is accessible
Distance between node  0 -> 0  is 0
Path     between node  0 -> 0  is:  0

 ------------------------ 

From node 0 to 1  is accessible
Distance between node  0 -> 1  is 1
Path     between node  0 -> 1  is:  0 -> 1

 ------------------------ 

From node 0 to 2  is accessible
Distance between node  0 -> 2  is 1
Path     between node  0 -> 2  is:  0 -> 2

 ------------------------ 

From node 0 to 3  is accessible
Distance between node  0 -> 3  is 2
Path     between node  0 -> 3  is:  0 -> 1 -> 3

 ------------------------ 

From node 0 to 4  is accessible
Distance between node  0 -> 4  is 2
Path     between node  0 -> 4  is:  0 -> 2 -> 4

 ------------------------ 

From node 0 to 5  is accessible
Distance between node  0 -> 5  is 3
Path     between node  0 -> 5  is:  0 -> 2 -> 4 -> 5

 ------------------------