Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Connections between nodes are given in the file
- 5
- 10
- 0,1
- 0,2
- 1,0
- 1,2
- 1,4
- 2,0
- 2,1
- 2,3
- 3,2
- 4,1
- read it and find adjacent list and adjacent matrix */
- import java.util.*;
- import java.io.*;
- public class AdjacentListMatrix {
- private static HashMap<String, ArrayList<String>> adjacentList;
- private static int numOfNodes;
- private static int numOfEdges;
- public static void main(String[] args) {
- adjacentList = new HashMap<>();
- readFile("Adjacent List.txt");
- System.out.println("\n* Adjacent List:");
- printAdjacentList();
- System.out.println("\n* Adjacent Matrix:");
- printAdjacentMatrix();
- }
- public static void readFile(String fileName) {
- try {
- File file = new File(fileName);
- Scanner scannedFile = new Scanner(file);
- numOfNodes = Integer.parseInt(scannedFile.nextLine());
- numOfEdges = Integer.parseInt(scannedFile.nextLine());
- String tempKey = "";
- ArrayList<String> tempList = new ArrayList<>();
- while(scannedFile.hasNextLine()) {
- String newLine = scannedFile.nextLine();
- String[] splittedLine = newLine.split(",");
- if (tempKey.equals("")) {
- tempKey = splittedLine[0];
- tempList.add(splittedLine[1]);
- }
- else if (tempKey.equals(splittedLine[0])) {
- tempList.add(splittedLine[1]);
- }
- else if (!tempKey.equals(splittedLine[0])) {
- adjacentList.put(tempKey, tempList);
- tempKey = splittedLine[0];
- tempList = new ArrayList<>();
- tempList.add(splittedLine[1]);
- }
- if (!scannedFile.hasNextLine()) {
- adjacentList.put(tempKey, tempList);
- }
- }
- }
- catch(FileNotFoundException ex) {
- ex.printStackTrace();
- }
- }
- public static void printAdjacentList() {
- for (String key : adjacentList.keySet()) {
- System.out.print(key + " : ");
- ArrayList<String> list = adjacentList.get(key);
- for (String val : list) {
- System.out.print(val + " ");
- }
- System.out.println();
- }
- }
- public static void printAdjacentMatrix() {
- for (int i = 0; i < numOfNodes; i++) {
- ArrayList<String> list = adjacentList.get(Integer.toString(i));
- for (int j = 0; j < numOfNodes; j++) {
- if (list.contains(Integer.toString(j)))
- System.out.print("1 ");
- else System.out.print("0 ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement