我如何以此创建邻接矩阵?

时间:2019-05-23 07:07:20

标签: java algorithm graph nodes edges

尝试将这些信息转换为邻接矩阵,但对操作方法感到困惑

import java.util.*;

public class graph {

  public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
    int adjMatrix[][];
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    while(stdin.hasNext()) {
      String[] str = stdin.nextLine().split("[\\s,]+");
      ArrayList<Integer> inner = new ArrayList<Integer>();
      for(int i = 0; i < str.length; i++) {
        inner.add(Integer.parseInt(str[i]));
      }
      list.add(inner);
    }
  }
}

将信息存储在arraylist的arraylist中。对于如何使它成为邻接矩阵的帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

如果您从标准输入中提取的数据有效,那么您应该能够构建邻接矩阵:

public static void main(String[] args) {
    String[] input = "1 2 5 \n3 4 2 \n".split("\n");
    int adjMatrix[][];
    int max = 0;
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    for(int i=0; i<input.length; i++) {
      String[] str = input[i].split("[\\s,]+");
      ArrayList<Integer> inner = new ArrayList<Integer>();
      for(int j = 0; j < str.length; j++) {
        inner.add(Integer.parseInt(str[j]));
      }
      max = Math.max(Math.max(max, inner.get(0)), inner.get(1));
      list.add(inner);
    }

    int[][] adjacencyMatrix = new int[max+1][max+1];

    for(int i=0; i<list.size(); i++) {
      int source = list.get(i).get(0);
      int dest = list.get(i).get(1);
      adjacencyMatrix[source][dest] += 1;
    }

    for(int i=0; i<adjacencyMatrix.length; i++) {
      for(int j=0; j<adjacencyMatrix[i].length; j++) {
        System.out.print(adjacencyMatrix[i][j]); 
      }
      System.out.println("");
    }
}

我没有考虑权重,因为它似乎对邻接矩阵不是很重要

答案 1 :(得分:0)

public static void main(String[] args) {

    Scanner stdin = new Scanner(System.in);

    int nodeCount = 0;

    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    while(stdin.hasNext()) {
        String[] str = stdin.nextLine().split("[\\s,]+");
        ArrayList<Integer> inner = new ArrayList<Integer>();
        for(int i = 0; i < str.length; i++) {

            int value = Integer.parseInt(str[i]);
            inner.add(value);

            if(value > nodeCount && i != str.length - 1){
                nodeCount = value;
            }
        }
        list.add(inner);
    }

    int adjMatrix[][] = new int[nodeCount + 1][nodeCount + 1];

    for(ArrayList<Integer> inner : list){
        adjMatrix[inner.get(0)][inner.get(1)] += 1;
    }

    for(int i = 0; i < nodeCount; i++){
        for(int j = 0; j < nodeCount; j++){
            System.out.print(adjMatrix[i][j] + " ");
        }
        System.out.println();
    }
}

答案 2 :(得分:0)

也许您应该以这样的方式作为起点。

public class AdjacencyMatrix {

    public static void main(String... args) {
        List<Edge> edges = readFromStdIn();
        Graph graph = new Graph(edges);
        int[][] adjacencyMatrix = graph.getAdjacencyMatrix();
        printMatrix(adjacencyMatrix);
    }

    private static List<Edge> readFromStdIn() {
        List<Edge> edges = new ArrayList<Edge>();
        try (Scanner scanner = new Scanner(System.in)) {
            boolean readOn = true;
            while (scanner.hasNext() && readOn) {
                String[] strings = scanner.nextLine().split("[\\s,]+");
                if (strings.length == 3) {
                    edges.add(new Edge(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]),
                            Integer.parseInt(strings[2])));
                } else {
                    readOn = false;
                }
            }
        }
        return edges;
    }

    private static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

class Edge {
    final int source;
    final int destination;
    final int weight;

    Edge(int source, int destination, int weight) {
        this.source = source;
        this.destination = destination;
        this.weight = weight;
    }
}

class Graph {
    final List<Edge> edges;

    Graph(List<Edge> edges) {
        this.edges = edges;
    }

    public int[][] getAdjacencyMatrix() {
        int n = getNodeCount();
        int[][] matrix = new int[n][n];
        for (Edge e : edges) {
            matrix[e.source][e.destination] = 1;
            // directed graph?
            matrix[e.destination][e.source] = 1;
        }
        return matrix;
    }

    int getNodeCount() {
        int maxNodeNumber = 0;
        for (Edge edge : edges) {
            if (edge.source > maxNodeNumber) {
                maxNodeNumber = edge.source;
            }
            if (edge.destination > maxNodeNumber) {
                maxNodeNumber = edge.destination;
            }
        }
        return maxNodeNumber + 1;
    }
}

它引入了一些类来为代码添加一些结构,避免在知道数组长度时列出列表。 此外:如果多次包含边,它将不会创建值大于1的条目。