Suppose you have below graph , which you wanted to represent in your program. How ?
There are multiple ways to represent, but most used are:
1. Adjacency matrix
2. Adjacency list.
I will show you how can we represent the above graph using adjacency list:
First of all what does adjacency list means ? it simply is the representation where each nodes neighbors will be stored in list.
Means against each node which has the neighbor we will have linked list
node 0 will have list of (1, 2)
node 1 will have list of (2,4,3)
so basically in java we can have a Map<Node, LinkedList<Node>> to represent the graph.
Here is the code below:
Github link
Github link
package madwani.sushil.model; import java.util.HashMap; import java.util.LinkedList; public class Graph { private HashMap<Node, LinkedList<Node>> adjacencyMap; private boolean directed; public Graph(boolean directed) { this.directed = directed; adjacencyMap = new HashMap<>(); } public HashMap<Node, LinkedList<Node>> getAdjacencyMap() { return adjacencyMap; } public void setAdjacencyMap(HashMap<Node, LinkedList<Node>> adjacencyMap) { this.adjacencyMap = adjacencyMap; } }
package madwani.sushil.model; public class Node {
int n; String name;
public Node(int n, String name) { this.n = n; this.name = name; }
public int getN() { return n; } public String getName() { return name; } }
package madwani.sushil.service; import madwani.sushil.model.Graph; import madwani.sushil.model.Node; import java.util.HashMap; import java.util.LinkedList;
public class GraphService {
public static void main(String[] args) { GraphService service = new GraphService(); service.print(service.getSampleGraph()); } public void addEdge(Graph graph, Node src, Node dest) { HashMap<Node, LinkedList<Node>> adjMap = graph.getAdjacencyMap(); LinkedList<Node> nodes = adjMap.get(src); if(nodes == null){ nodes = new LinkedList<>(); nodes.add(dest); } if(!nodes.contains(dest)) { nodes.add(dest); } adjMap.put(src,nodes); graph.setAdjacencyMap(adjMap); } public void print(Graph graph){ for (Node n: graph.getAdjacencyMap().keySet()){ LinkedList<Node> list = graph.getAdjacencyMap().get(n); if(list !=null && list.size()!=0) { System.out.print( n.getN() + " -> "); list.stream().forEach(e-> System.out.print(e.getN() + " -> ")); System.out.print("null"); System.out.println(); } } } public Graph getSampleGraph(){ Graph g = new Graph(false); Node _0 = new Node(0,"zero"); Node _1 = new Node(1,"one"); Node _2 = new Node(2,"two"); Node _3 = new Node(3,"three"); Node _4 = new Node(4,"four"); Node _5 = new Node(5,"five"); addEdge(g,_0,_1); addEdge(g,_0,_2); addEdge(g,_1,_3); addEdge(g,_1,_2); addEdge(g,_1,_4); addEdge(g,_2,_4); addEdge(g,_2,_3); addEdge(g,_4,_5); return g; } }
Code Output:
0 -> 1 -> 2 -> null
2 -> 4 -> 3 -> null
1 -> 3 -> 2 -> 4 -> null
4 -> 5 -> null
Process finished with exit code 0
No comments:
Post a Comment