Change my input to a different format

I ask you for help because I am stuck. I have an input in this format:

6 <- number of vertices

0 1 2 <- vertices directly connected to the vertex 0 by the edge

1 0 3 4

I need my program to have this:

int[][] edges = {
   {0,1}, {0,2}, 
   {1,2}, {1,3}, 
   {2,5},
   {3,2}, {3,4},
   {5,4}
};

I got stuck and thought I might have to work with a list? This is what I had so far:

public class Part1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int k = scanner.nextInt(); // number of vertices
        String[] input = new String[k];
        int[][] edges;
        String[] tokens = new String[k];
        int[] vertices = new int[k];
        int[] integers = new int[k];
        int p = 0;

        for (int i = 0; i < k; i++) {
            vertices[i] = i;
            input[i] = scanner.nextLine();
            tokens = input[i].split("[\\s+]");
            integers[i] = Integer.parseInt(tokens[i].trim());
            for (int j = 0; j < integers.length - 1; j++) {
                edges[p][i] = integers[0];
                edges[p][2] = integers[j];
                p++;

            }
        }
    }
}

Hope someone can help me.

+3
source share
2 answers

I would ask you to present your schedule in a different way. The usual way to present a graph (and a convenient way for many basic graph algorithms) is Vector [], an array of lists declared this way.

Vector<Integer> graph = new Vector<Integer>[number_of_vertices];

[i] , i. , , . :

for (int i = 0; i < k; i++) {
  String line = scanner.nextLine();
  tokens = line.split(" ");
  int from = Integer.parseInt(line[0]);
  for (int j = 1; j < tokens.length; j++) {
    graph[from].add(Integer.parseInt(tokens[j]));
  }
}

EDIT: . kant , .

+2

, Java . :

Map<Integer,Vector<Integer>> graph = new HashMap<Integer, Vector<Integer>>();

for (int i = 0; i < k; i++) {
  String line = scanner.nextLine();
  tokens = line.split(" ");
  int from = Integer.parseInt(line[0]);
  Vector<Integer> = v new Vector<Integer>();
  for (int j = 1; j < tokens.length; j++) {
    v.add(Integer.parseInt(tokens[j]));
  }
  graph.put(from, v);

}

, :

  Vector<Integer> v = graph.get(0);
+1

All Articles