Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
My journey with you | All you wish will be here !!!
My journey with you | All you wish will be here !!!
Graphs are one of the fundamental data structures in computer science. Understanding graphs and their properties is essential for tackling problems in areas such as networking, social media analysis, and even game development.
A graph is a collection of nodes (also called vertices) and edges (connections between nodes). In a graph, nodes can represent objects, and edges represent the relationships between those objects.
There are two primary types of graphs:
Graphs can be represented in two major ways:
1
if there is an edge from node i to node j, otherwise 0
.Example in Python (Adjacency List Representation):
pythonCopy codegraph = {
0: [1, 4],
1: [0, 2],
2: [1, 3],
3: [2],
4: [0]
}
Example of Adjacency List Representation in Java:
javaCopy codeimport java.util.*;
public class Graph {
Map<Integer, List<Integer>> graph = new HashMap<>();
// Add edge
public void addEdge(int node, int neighbor) {
graph.computeIfAbsent(node, k -> new ArrayList<>()).add(neighbor);
}
// Print the graph
public void printGraph() {
for (int node : graph.keySet()) {
System.out.print(node + " -> ");
for (int neighbor : graph.get(node)) {
System.out.print(neighbor + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Graph g = new Graph();
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 2);
g.addEdge(4, 0);
g.printGraph();
}
}