logo

Java Graph

U Javi, Grafikon je podatkovna struktura koja pohranjuje određene podatke. Koncept graf je ukraden iz matematike koja ispunjava potrebe polja informatike. Predstavlja mrežu koja povezuje više točaka međusobno. U ovom odjeljku ćemo detaljno naučiti strukturu podataka Java Graph-a. Također, naučit ćemo vrste Graf , njihovu implementaciju i obilazak preko grafa.

Grafikon

A graf je Graph Terminology

Vrh: Vrhovi su točke koje spajaju rubove. Predstavlja podatke. Također je poznat kao čvor. Označava se kružićem i mora biti označena. Za konstruiranje grafa mora postojati barem čvor. Na primjer, kuća, autobusna stanica itd.

Rub: Brid je linija koja povezuje dva vrha. Predstavlja odnos između vrhova. Bridovi su označeni linijom. Na primjer, staza do autobusne stanice od vaše kuće.

Težina: Označeno je do ruba. Na primjer, udaljenost između dva grada je 100 km, tada se udaljenost naziva težina za rub.

java program

Staza: Put je način da se stigne do odredišta od početne točke niza.

Vrste grafova

    Ponderirani grafikon:U ponderiranom grafu svaki rub sadrži nešto podaci (težina) kao što je udaljenost, težina, visina itd. Označava se kao w(e). Koristi se za izračunavanje cijene prijelaza od jednog vrha do drugog. Sljedeća slika predstavlja ponderirani graf.
    Java Graph Neponderirani grafikon:Graf u kojem rubovi nisu pridruženi nijednoj vrijednosti naziva se neponderirani graf. Sljedeća slika predstavlja neponderirani graf.
    Java Graph Usmjereni grafikon:Graf u kojem bridovi predstavljaju smjer naziva se usmjereni graf. U usmjerenom grafu umjesto linija (bridova) koristimo strelice. Smjer označava put od jednog do drugog čvora. Imajte na umu da se u usmjerenom grafu možemo kretati u jednom ili u oba smjera. Sljedeća slika predstavlja usmjereni graf.
    Java Graph Neusmjereni graf:Graf u kojem su bridovi dvosmjerni naziva se neusmjereni graf. U neusmjerenom grafu možemo ići u bilo kojem smjeru. Imajte na umu da za povratak možemo koristiti isti put kojim smo prošli. Dok se u usmjerenom grafu ne možemo vratiti s istog puta.
    Java Graph Povezani grafikon:Za graf se kaže da je povezan ako postoji barem jedan put između svakog para vrhova. Imajte na umu da je graf sa samo vrhom povezan graf.
    Java Graph
    Postoje dvije vrste povezanih grafova.
      Tjedni povezani grafikon:Graf u kojem se čvorovi ne mogu posjetiti jednim putem naziva se tjednim povezanim grafom.
      Java Graph Snažno povezani grafikon:Graf u kojem se čvorovi mogu posjetiti jednim putem naziva se snažno povezani graf.
      Java Graph
    Isključeni grafikon:Za graf se kaže da je nepovezan ako ne postoji put između para vrhova i naziva se nepovezanim grafom. Nepovezani graf može se sastojati od dva ili više povezanih grafova.
    Java Graph Višestruki grafikon:Graf koji ima više rubova koji povezuju isti par čvorova. Sljedeća slika predstavlja multigraf.
    Java Graph Gusti grafikon:Graf u kojem je broj bridova blizu maksimalnog broja bridova naziva se gustim grafom. Sljedeća slika predstavlja gusti graf.
    Java Graph Rijetki grafikon:Graf u kojem je broj bridova blizu minimalnog broja bridova naziva se rijetkim grafom. To može biti nepovezani graf. Sljedeća slika predstavlja rijetki graf.
    Java Graph

Implementacija Java Graph-a

Za implementaciju grafova u Javu ćemo koristiti Generički razreda. Za stvaranje objekta Java Generic klase koristimo sljedeću sintaksu:

 BaseType obj = new BaseType (); 

Zapamtite da ne možemo koristiti primitivni tip za tip parametra.

Kreirajmo Java program koji implementira Graph.

GraphImplementation.java

 import java.util.*; class Graph { //creating an object of the Map class that stores the edges of the graph private Map<t, list> map = new HashMap(); //the method adds a new vertex to the graph public void addNewVertex(T s) { map.put(s, new LinkedList()); } //the method adds an edge between source and destination public void addNewEdge(T source, T destination, boolean bidirectional) { // if (!map.containsKey(source)) addNewVertex(source); if (!map.containsKey(destination)) addNewVertex(destination); map.get(source).add(destination); if (bidirectional == true) { map.get(destination).add(source); } } //the method counts the number of vertices public void countVertices() { System.out.println(&apos;Total number of vertices: &apos;+ map.keySet().size()); } //the method counts the number of edges public void countEdges(boolean bidirection) { //variable to store number of edges int count = 0; for (T v : map.keySet()) { count = count + map.get(v).size(); } if (bidirection == true) { count = count / 2; } System.out.println(&apos;Total number of edges: &apos;+ count); } //checks a graph has vertex or not public void containsVertex(T s) { if (map.containsKey(s)) { System.out.println(&apos;The graph contains &apos;+ s + &apos; as a vertex.&apos;); } else { System.out.println(&apos;The graph does not contain &apos;+ s + &apos; as a vertex.&apos;); } } //checks a graph has edge or not //where s and d are the two parameters that represent source(vertex) and destination (vertex) public void containsEdge(T s, T d) { if (map.get(s).contains(d)) { System.out.println(&apos;The graph has an edge between &apos;+ s + &apos; and &apos; + d + &apos;.&apos;); } else { System.out.println(&apos;There is no edge between &apos;+ s + &apos; and &apos; + d + &apos;.&apos;); } } //prints the adjacencyS list of each vertex //here we have overridden the toString() method of the StringBuilder class @Override public String toString() { StringBuilder builder = new StringBuilder(); //foreach loop that iterates over the keys for (T v : map.keySet()) { builder.append(v.toString() + &apos;: &apos;); //foreach loop for getting the vertices for (T w : map.get(v)) { builder.append(w.toString() + &apos; &apos;); } builder.append(&apos;
&apos;); } return (builder.toString()); } } //creating a class in which we have implemented the driver code public class GraphImplementation { public static void main(String args[]) { //creating an object of the Graph class Graph graph=new Graph(); //adding edges to the graph graph.addNewEdge(0, 1, true); graph.addNewEdge(0, 4, true); graph.addNewEdge(1, 2, true); graph.addNewEdge(1, 3, false); graph.addNewEdge(1, 4, true); graph.addNewEdge(2, 3, true); graph.addNewEdge(2, 4, true); graph.addNewEdge(3, 0, true); graph.addNewEdge(2, 0, true); //prints the adjacency matrix that represents the graph System.out.println(&apos;Adjacency List for the graph:
&apos;+ graph.toString()); //counts the number of vertices in the graph graph.countVertices(); //counts the number of edges in the graph graph.countEdges(true); //checks whether an edge is present or not between the two specified vertices graph.containsEdge(3, 4); graph.containsEdge(2, 4); //checks whether vertex is present or not graph.containsVertex(3); graph.containsVertex(5); } } </t,>

Izlaz:

Java Graph

Implementacija usmjerenog grafa

DirectedGraph.java

 import java.util.*; //Creating a class named Edge that stores the edges of the graph class Edge { //the variable source and destination represent the vertices int s, d; //creating a constructor of the class Edge Edge(int s, int d) { this.s = s; this.d = d; } } //a class to represent a graph object class Graph { //note that we have created an adjacency list (i.e. List of List) List<list> adjlist = new ArrayList(); //creating a constructor of the class Graph that construct a graph public Graph(List edges) { int n = 0; //foreach loop that iterates over the edge for (Edge e: edges) { //determines the maximum numbered vertex n = Integer.max(n, Integer.max(e.s, e.d)); } //reserve the space for the adjacency list for (int i = 0; i <= 1 n; i++) { adjlist.add(i, new arraylist()); } adds the edges to undirected graph for (edge current: edges) allocate node in adjacency list from source destination adjlist.get(current.s).add(current.d); function print representation of a public static void showgraph(graph graph) int s="0;" determines size n="graph.adjlist.size();" while (s ' + d ')	'); system.out.println(); increments by s++; implementing driver code class directedgraph main (string args[]) creating edge(0, 1), edge(1, 2), edge(2, 4), edge(4, 1),new edge(3, 5), edge(5, 1)); construct given graph(edges); prints that represents graph.showgraph(graph); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/java-graph-13.webp" alt="Java Graph"> <h2>Implementation of Weighted Graph</h2> <p> <strong>WeightedGraph.java</strong> </p> <pre> import java.util.*; //the class stores the edges of the graph class Edge { int s, d, w; //creating a constructor of the class Edge Edge(int src, int dest, int weight) { this.s = src; this.d = dest; this.w = weight; } } //a class to store adjacency list nodes class Node { int value, weight; //creating a constructor of the class Vertex Node(int value, int weight) { this.value = value; this.weight = weight; } //overrides the toString() method @Override public String toString() { return this.value + &apos; (&apos; + this.weight + &apos;)&apos;; } } //a class to represent a graph object class Graph { //note that we have created an adjacency list (i.e. List of List) List<list> adjlist = new ArrayList(); //creating a constructor of the class Graph that creates graph public Graph(List edges) { //find the maximum numbered vertex int n = 0; //iterates over the edges of the graph for (Edge e: edges) { //determines the maximum numbered vertex n = Integer.max(n, Integer.max(e.s, e.d)); } //reserve the space for the adjacency list for (int i = 0; i <= 1 n; i++) { adjlist.add(i, new arraylist()); } adds the edges to undirected graph for (edge e: edges) creating a node (from source destination) in adjacency list adjlist.get(e.s).add(new node(e.d, e.w)); uncomment following statement adj.get(e.dest).add(new node(e.src, e.weight)); method that prints of public static void printgraph(graph graph) int src="0;" n="graph.adjlist.size();" system.out.printf('adjacency is: '); while (src %s	', src, edge); system.out.println(); increments by src++; implementing driver code class weightedgraph main (string args[]) with their associated weight edge(1, 4, 3), edge(4, 2, 5), edge(2, 5, 10), edge(5, 1, 6), edge(3, 9), 1), 2)); creates declared above graph(edges); corresponding graph.printgraph(graph); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/java-graph-14.webp" alt="Java Graph"> <h2>Graph Traversal</h2> <p>Traversal over the graph means visit each and every vertex and edge at least once. To traverse over the graph, Graph data structure provides two algorithms:</p> <ul> <li>Depth-First Search (DFS)</li> <li>Breadth-First Search (DFS)</li> </ul> <h3>Depth-First Search (DFS)</h3> <p> <a href="/dfs-algorithm">DFS algorithm</a> is a recursive algorithm that is based on the backtracking concept. The algorithm starts from the initial node and searches in depth until it finds the goal node (a node that has no child). Backtracking allows us to move in the backward direction on the same path from which we have traversed in the forward direction.</p> <p>Let&apos;s implement the DFS algorithm in a Java program.</p> <p> <strong>DepthFirstSearch.java</strong> </p> <pre> import java.io.*; import java.util.*; //creates an undirected graph class Graph { //stores the number of vertices private int Vertices; //creates a linked list for the adjacency list of the graph private LinkedList adjlist[]; //creating a constructor of the Graph class Graph(int count_v) { //assigning the number of vertices to the passed parameter Vertices = count_v; adjlist = new LinkedList[count_v]; //loop for creating the adjacency lists for (int i=0; i<count_v; 3 10 ++i) adjlist[i]="new" linkedlist(); } method that adds a new edge to the graph void addnewedge(int v, int w) { adjlist[v].add(w); add w v's list. logic of dfs traversal starts from root node traversaldfs(int boolean vnodelist[]) if current (root node) is visited, it vnodelist vnodelist[v]="true;" system.out.print(v+' '); detrmines negihboring nodes iterates over list iterator i="adjlist[v].listIterator();" while (i.hasnext()) returns next element in iteration and store variable n (!vnodelist[n]) calling function performs depth first traversaldfs(n, vnodelist); dfs(int v) creates an array type for visited initially all are unvisited visited[]="new" boolean[vertices]; call recursive traversaldfs() traversaldfs(v, visited); implementing driver code public class depthfirstsearch static main(string args[]) having vertices g="new" graph(10); edges g.addnewedge(1, 2); g.addnewedge(2, 3); g.addnewedge(3, 4); g.addnewedge(4, 5); g.addnewedge(5, 7); 6); print sequencnce which bfs done system.out.println('depth-first is: (as g.dfs(1); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/java-graph-15.webp" alt="Java Graph"> <h3>Breadth First Search (BFS)</h3> <p> <a href="/bfs-algorithm">BFS algorithm</a> is the most common approach to traverse over the graph. The traversal starts from the source node and scans its neighboring nodes (child of the current node). In short, traverse horizontally and visit all the nodes of the current layer. After that, move to the next layer and perform the same.</p> <p>Let&apos;s implement the BFS algorithm in a Java program.</p> <p> <strong>BreadthFirstSearch.java</strong> </p> <pre> import java.io.*; import java.util.*; //creates an undirected graph class Graph { //stores the number of vertices private int vertices; //creates a linked list for the adjacency list of the graph private LinkedList adjlist[]; //creating a constructor of the Graph class Graph(int count_v) { //assigning the number of vertices to the passed parameter vertices = count_v; adjlist = new LinkedList[count_v]; //loop for creating the adjacency lists for (int i=0; i<count_v; 10 ++i) adjlist[i]="new" linkedlist(); } method that adds a new edge to the graph void addnewedge(int v, int w) { adjlist[v].add(w); traversal starts from root node traversalbfs(int rnode) creates an array of boolean type for visited initially all nodes are unvisited visitednode[]="new" boolean[vertices]; creating another list storing linkedlist vnodelist="new" if current (root node) is visited, add it visitednode[rnode]="true;" inserts into vnodelist.add(rnode); while loop executes until we have (vnodelist.size() !="0)" deque entry queue and process poll() retrieves removes head (first element) this rnode="vnodelist.poll();" system.out.print(rnode+' '); detrmines negihboring iterates over iterator i="adjlist[rnode].listIterator();" (i.hasnext()) returns next element in iteration store variable n checks or not (!visitednode[n]) above if-statement true, visits visitednode[n]="true;" vnodelist.add(n); implementing driver code public class breadthfirstsearch static main(string args[]) having vertices graph(10); edges graph.addnewedge(2, 5); graph.addnewedge(3, graph.addnewedge(1, 2); 4); graph.addnewedge(4, 1); graph.addnewedge(6, graph.addnewedge(5, 6); 3); graph.addnewedge(7, 7); print sequence which bfs execute system.out.println('breadth-first is: graph.traversalbfs(2); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/19/java-graph-16.webp" alt="Java Graph"> <hr></count_v;></pre></count_v;></pre></=></list></pre></=></list>