0% found this document useful (0 votes)
2 views

Graph

A graph is a non-linear data structure composed of nodes (vertices) and edges, used to model real-world problems like social networks and transportation. Key features include directed/undirected edges, weighted/unweighted graphs, and operations such as adding/removing vertices and edges, as well as traversal methods like BFS and DFS. Pros include flexible representation and efficient connectivity, while cons involve complexity and memory overhead.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Graph

A graph is a non-linear data structure composed of nodes (vertices) and edges, used to model real-world problems like social networks and transportation. Key features include directed/undirected edges, weighted/unweighted graphs, and operations such as adding/removing vertices and edges, as well as traversal methods like BFS and DFS. Pros include flexible representation and efficient connectivity, while cons involve complexity and memory overhead.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Graph: Definition, Features, Operations, Pros and Cons

1. Definition of Graph

A graph is a non-linear data structure that consists of a collection of nodes (vertices) and a collection of
edges connecting pairs of nodes. Graphs are used to represent various real-world problems like social
networks, transportation networks, and web pages.

 Vertices (Nodes): The entities or objects in the graph.

 Edges (Arcs): The connections between the nodes. Each edge can be directed (one-way) or
undirected (two-way).

There are two main types of graphs:

 Directed Graph (Digraph): In a directed graph, edges have a direction, i.e., they go from one
vertex to another.

 Undirected Graph: In an undirected graph, edges have no direction; they simply connect two
vertices.

Graphs can also be weighted or unweighted:

 Weighted Graph: Each edge has a weight (cost).

 Unweighted Graph: Edges don’t have weights.

2. Features of Graphs

 Vertices and Edges: Fundamental components of a graph.

 Directed/Undirected: Determines if the edges have a direction.

 Weighted/Unweighted: Determines if edges have a weight or cost.

 Cyclic/Acyclic: A graph may contain cycles (paths where the start and end are the same) or may
not.

3. Operations on Graphs

Common operations on graphs include:

1. Add Vertex: Adds a new vertex to the graph.

2. Add Edge: Adds an edge between two vertices.

3. Remove Vertex: Removes a vertex and its associated edges.

4. Remove Edge: Removes an edge between two vertices.

5. BFS (Breadth-First Search): Traverses the graph level by level.

6. DFS (Depth-First Search): Traverses the graph deeply, visiting one vertex before backtracking.

7. Shortest Path: Finds the shortest path between two vertices (e.g., Dijkstra’s algorithm).
8. Cycle Detection: Detects whether a cycle exists in the graph.

9. Graph Traversal: Traverses the graph to visit all nodes.

4. Pros and Cons of Graphs

Pros:

 Flexible Representation: Graphs can represent complex relationships like social networks, roads,
etc.

 Efficient for Connectivity: Great for representing connected structures.

 Variety of Applications: Can be used for shortest path, network flow, resource allocation, etc.

Cons:

 Complexity: Graph algorithms can be complex and computationally expensive.

 Memory Overhead: Graphs can consume more memory, especially when using adjacency
matrices for sparse graphs.

 Harder to Implement: Graphs often require more careful handling in terms of structure and
algorithms.
Example Java Code for Graph

Let's implement a simple graph using an adjacency list in Java and include BFS and DFS traversal
operations.

import java.util.*;

class Graph {

private Map<Integer, List<Integer>> adjacencyList;

// Constructor to initialize the graph

public Graph() {

adjacencyList = new HashMap<>();

// Add a vertex to the graph

public void addVertex(int vertex) {

adjacencyList.putIfAbsent(vertex, new ArrayList<>());

// Add an edge to the graph

public void addEdge(int from, int to) {

adjacencyList.putIfAbsent(from, new ArrayList<>());

adjacencyList.putIfAbsent(to, new ArrayList<>());

adjacencyList.get(from).add(to); // Directed edge

adjacencyList.get(to).add(from); // For undirected graph

// BFS (Breadth-First Search)

public void BFS(int start) {

Set<Integer> visited = new HashSet<>();


Queue<Integer> queue = new LinkedList<>();

visited.add(start);

queue.add(start);

while (!queue.isEmpty()) {

int vertex = queue.poll();

System.out.print(vertex + " ");

for (int neighbor : adjacencyList.get(vertex)) {

if (!visited.contains(neighbor)) {

visited.add(neighbor);

queue.add(neighbor);

System.out.println();

// DFS (Depth-First Search)

public void DFS(int start) {

Set<Integer> visited = new HashSet<>();

DFSUtil(start, visited);

System.out.println();

// Helper method for DFS (recursive)

private void DFSUtil(int vertex, Set<Integer> visited) {

visited.add(vertex);
System.out.print(vertex + " ");

for (int neighbor : adjacencyList.get(vertex)) {

if (!visited.contains(neighbor)) {

DFSUtil(neighbor, visited);

// Print the graph

public void printGraph() {

for (Map.Entry<Integer, List<Integer>> entry : adjacencyList.entrySet()) {

System.out.print(entry.getKey() + " -> ");

for (Integer neighbor : entry.getValue()) {

System.out.print(neighbor + " ");

System.out.println();

public class Main {

public static void main(String[] args) {

Graph graph = new Graph();

// Add vertices

graph.addVertex(0);

graph.addVertex(1);

graph.addVertex(2);
graph.addVertex(3);

graph.addVertex(4);

// Add edges

graph.addEdge(0, 1);

graph.addEdge(0, 4);

graph.addEdge(1, 2);

graph.addEdge(1, 3);

graph.addEdge(2, 4);

// Print the graph

System.out.println("Graph:");

graph.printGraph();

// BFS traversal

System.out.println("\nBFS starting from vertex 0:");

graph.BFS(0);

// DFS traversal

System.out.println("\nDFS starting from vertex 0:");

graph.DFS(0);

}
Explanation of the Code:

1. Graph Class:

o Adjacency List: We use a HashMap<Integer, List<Integer>> to represent the graph where


each key is a vertex and the value is the list of its adjacent vertices.

o addVertex(): Adds a vertex if it does not already exist.

o addEdge(): Adds an edge between two vertices. This creates an undirected edge by
adding the connection in both directions.

o BFS(): Implements Breadth-First Search using a queue.

o DFS(): Implements Depth-First Search using recursion.

2. Main Class:

o Add Vertices: Vertices 0, 1, 2, 3, and 4 are added.

o Add Edges: Edges are added between various vertices.

o Print the Graph: The adjacency list is printed.

o BFS and DFS Traversal: Both BFS and DFS algorithms are tested starting from vertex 0.

Output:

Graph:

0 -> 1 4

1 -> 0 2 3

2 -> 1 4

3 -> 1

4 -> 0 2

BFS starting from vertex 0:

01423

DFS starting from vertex 0:

01243

You might also like