logo

Java-graf

I Java er Kurve er en datastruktur som lagrer en viss data. Konseptet med kurve har blitt stjålet fra matematikken som oppfyller behovet til informatikkfeltet. Det representerer et nettverk som kobler flere punkter til hverandre. I denne delen vil vi lære Java Graph-datastruktur i detalj. Dessuten vil vi lære typer grafer , implementeringen av dem , og kryssing over grafen.

Kurve

EN kurve er en grafterminologi

Toppunkt: Topppunkter er punktet som skjøter kanter. Den representerer dataene. Det er også kjent som en node. Det er merket med en sirkel og det må merkes. For å konstruere en graf må det være minst en node. For eksempel hus, bussholdeplass o.l.

Kant: En kant er en linje som forbinder to hjørner. Den representerer forholdet mellom toppunktene. Kanter er merket med en linje. For eksempel en sti til bussholdeplassen fra huset ditt.

Vekt: Den er merket til kant. For eksempel er avstanden mellom to byer 100 km, da kalles avstanden vekt for kanten.

Sti: Banen er en måte å nå en destinasjon fra startpunktet i en sekvens.

Typer grafer

    Vektet graf:I en vektet graf inneholder hver kant noen data (vekt) som avstand, vekt, høyde osv. Det betegnes som w(e). Den brukes til å beregne kostnadene ved å krysse fra ett toppunkt til et annet. Følgende figur representerer en vektet graf.
    Java-graf Uvektet graf:En graf der kanter ikke er assosiert med noen verdi kalles en uvektet graf. Følgende figur representerer en uvektet graf.
    Java-graf Regissert graf:En graf der kanter representerer retning kalles en rettet graf. I en rettet graf bruker vi piler i stedet for linjer (kanter). Retning angir veien for å nå fra en node til en annen node. Merk at i en rettet graf kan vi bevege oss enten i én retning eller i begge retninger. Følgende figur representerer en rettet graf.
    Java-graf Udirigert graf:En graf der kantene er toveis kalles en urettet graf. I en urettet graf kan vi krysse i alle retninger. Merk at vi kan bruke samme vei for retur som vi har krysset. Mens i den rettede grafen kan vi ikke gå tilbake fra samme vei.
    Java-graf Tilkoblet graf:En graf sies å være koblet hvis det eksisterer minst én bane mellom hvert par av hjørner. Merk at en graf med bare et toppunkt er en sammenkoblet graf.
    Java-graf
    Det finnes to typer sammenkoblede grafer.
      Ukentlig tilkoblet graf:En graf der noder ikke kan besøkes av en enkelt sti kalles en ukentlig tilkoblet graf.
      Java-graf Sterkt koblet graf:En graf der noder kan besøkes av en enkelt sti kalles en sterkt koblet graf.
      Java-graf
    Frakoblet graf:En graf sies å være frakoblet hvis det ikke er noen bane mellom et par hjørner, kalles en frakoblet graf. En frakoblet graf kan bestå av to eller flere tilkoblede grafer.
    Java-graf Multi Graph:En graf som har flere kanter som forbinder det samme nodeparet. Følgende figur representerer en multigraf.
    Java-graf Tett graf:En graf der antall kanter er nær maksimalt antall kanter, grafen kalles den tette grafen. Følgende figur representerer en tett graf.
    Java-graf Sparsom graf:En graf der antall kanter er nær det minimale antallet kanter, grafen kalles den sparsomme grafen. Det kan være en frakoblet graf. Følgende figur representerer en sparsom graf.
    Java-graf

Java grafimplementering

For implementering av grafer i Java vil vi bruke Generisk klasse. For å lage et objekt av Java Generic-klassen bruker vi følgende syntaks:

 BaseType obj = new BaseType (); 

Husk at vi ikke kan bruke primitiv type for parametertype.

La oss lage et Java-program som implementerer 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,>

Produksjon:

Java-graf

Implementering av Directed Graph

RegissertGraph.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>