I have an array of strings that represents the edges of a graph.
For example:
["6 11", "9 5", "11 9", "15 9", "13 15", "12 14", "15 16", "1 16"]
Now I want to create a graph for this so I can see how many nodes are connected and how many are not connected. I am not sure what approach to follow for this.
I have used a Map in my program but I am not able to group the nodes properly in my code:
public static void process(int n, List<String> input) { Map<Integer, Set<Integer>> map = new HashMap<>(); for (String in : input) { String[] arr = in.split(" "); int a1 = Integer.parseInt(arr[0]); int a2 = Integer.parseInt(arr[1]); int first = Math.min(a1, a2); int second = Math.max(a1, a2); if (map.size() == 0) { Set<Integer> s = new HashSet<>(); s.add(first); s.add(second); map.put(first, s); continue; } boolean found = false; for (int k : map.keySet()) { Set<Integer> set = map.get(k); if (set.contains(first)) { map.get(k).add(second); found = true; break; } if (set.contains(second)) { map.get(k).add(first); found = true; break; } } if (!found) { Set<Integer> s = new HashSet<>(); s.add(first); s.add(second); map.put(first, s); } } System.out.println(map); }
Now with this program I am getting a map with below values:
{5=[16, 1, 5, 9, 11, 13, 15], 6=[6, 11], 12=[12, 14]}
The problem here is I already have 11 for map key = 5. So node 6 should be added to the set for key = 5 itself. So the map should look like this:
{5=[16, 1, 5, 9, 11, 13, 15, 6], 12=[12, 14]}
How to do this, what approach I need to follow here? Here I used a map just for convenience because in a later step I wanted to count the size of each key means: 5 has 8 nodes, 12 has 2 nodes, etc. Nodes which are not having edges are 2, 3, 4, 7, 8, 10.
https://stackoverflow.com/questions/65745596/how-to-build-a-graph-from-given-string-of-pairs January 16, 2021 at 09:20AM
没有评论:
发表评论