An undirected graph is a fundamental graph data structure in which edges do not have a specific direction. Unlike a directed graph, where connections move from one vertex to another in a particular direction, an undirected graph represents a two-way relationship between connected vertices. If vertex A is connected to vertex B, then vertex B is also connected to vertex A. Undirected graphs are commonly used in social networks, computer networks, road maps, and communication systems. In this article, we will understand undirected graphs, their terminology, types, representations, operations, and implementation using JavaScript.
Table of Contents
What Is an Undirected Graph?
An undirected graph is a graph in which edges do not have a specific direction. Each edge represents a connection between two vertices, and the connection works in both directions.
An undirected graph is generally represented as G = (V, E)
Where:
- G: Represents the graph.
- V: Represents the set of vertices or nodes.
- E: Represents the set of undirected edges.
For example, if vertex A is connected to vertex B, the connection can be represented as: A — B
This means that A is connected to B, and B is also connected to A. Undirected graphs are useful for representing relationships where both connected entities have an equal or mutual connection.
How Does an Undirected Graph Work?
In an undirected graph, an edge connects two vertices without specifying which vertex is the starting point or destination.
Consider an undirected graph with the following edges:
-
A — B
-
A — C
-
B — D
-
C — D
These connections indicate that:
- Vertex A is connected to B and C.
- Vertex B is connected to A and D.
- Vertex C is connected to A and D.
- Vertex D is connected to B and C.
If a connection exists between A and B, we can travel from A to B as well as from B to A.
This two-way relationship is the main characteristic of an undirected graph.
Basic Terminology of Undirected Graphs
Understanding the basic terminology of undirected graphs helps in learning graph algorithms and solving programming problems.
- Vertex: A vertex is an individual node in a graph. It represents an object, location, person, or entity.
- Edge: An edge is a connection between two vertices. In an undirected graph, an edge does not have a direction.
- Adjacent Vertices: Two vertices are adjacent if they are directly connected by an edge. For example, if an edge connects A and B, then A and B are adjacent vertices.
- Degree of a Vertex: The degree of a vertex is the total number of edges connected to that vertex. For example, if vertex A is connected to three other vertices, its degree is 3. A self-loop contributes 2 to the degree of its vertex in a standard undirected graph.
- Path: A path is a sequence of vertices connected through edges. For example, A — B — C represents a path from A to C.
- Cycle: A cycle is a path that starts and ends at the same vertex, with no repeated vertices or edges other than the starting and ending vertex.
- Self-Loop: A self-loop is an edge that connects a vertex to itself. For example, A — A represents a self-loop.
- Connected Graph: An undirected graph is connected if there is a path between every pair of vertices.
- Disconnected Graph: An undirected graph is disconnected if at least one pair of vertices does not have a path connecting them.
- Weighted Undirected Graph: A weighted undirected graph is a graph in which every edge has an associated value called a weight. The weight may represent distance, cost, time, or another measurable value.
Types of Undirected Graphs
Undirected graphs can be classified into different types based on their structure and properties.
- Simple Graph: A simple graph does not contain self-loops or multiple edges between the same pair of vertices.
- Multigraph: A multigraph allows multiple edges between the same pair of vertices. Depending on the definition being used, self-loops may also be allowed.
- Weighted Undirected Graph: A weighted undirected graph assigns a weight to each edge.
- For example, an edge connecting A and B may have a weight of 10, representing the distance or cost between them.
- Complete Graph: A complete graph is an undirected graph in which every pair of distinct vertices is connected by an edge.
- For a simple complete undirected graph containing V vertices, the total number of edges is: E = V × (V − 1) / 2
- Connected Graph: A connected graph has a path between every pair of vertices.
- Disconnected Graph: A disconnected graph contains at least two vertices that cannot reach each other through any path.
- Cyclic Graph: A cyclic graph contains at least one cycle.
- Acyclic Graph: An acyclic graph does not contain any cycle. A connected, undirected, acyclic graph is called a tree.
- Bipartite Graph: A bipartite graph is an undirected graph whose vertices can be divided into two separate sets such that every edge connects a vertex from one set to a vertex from the other set.
Undirected Graph Representation
An undirected graph can be represented using different data structures in programming.
The two most commonly used representations are:
- Adjacency List.
- Adjacency Matrix.
Both representations store vertices and their connections, but they use different approaches.
Adjacency List Representation
An adjacency list stores each vertex along with a list of all its adjacent vertices.
In an undirected graph, when an edge is added between two vertices, both vertices are added to each other's adjacency lists.
For example, consider these undirected edges:
- A — B
- A — C
- B — D
- C — D
The adjacency list is:
- A: B, C
- B: A, D
- C: A, D
- D: B, C
In JavaScript, an adjacency list can be implemented using a Map.
// This program creates an undirected graph using an adjacency list.
const graph = new Map();
function addVertex(vertex) {
if (!graph.has(vertex)) {
graph.set(vertex, []);
}
}
function addEdge(vertex1, vertex2) {
addVertex(vertex1);
addVertex(vertex2);
graph.get(vertex1).push(vertex2);
graph.get(vertex2).push(vertex1);
}
addEdge("A", "B");
addEdge("A", "C");
addEdge("B", "D");
addEdge("C", "D");
console.log(graph);
Output:
Map(4) {
'A' => [ 'B', 'C' ],
'B' => [ 'A', 'D' ],
'C' => [ 'A', 'D' ],
'D' => [ 'B', 'C' ]
}
In this implementation:
- addVertex() creates a vertex if it does not already exist.
- addEdge() creates a connection between two vertices.
- Both vertices are added to each other's adjacency lists because the connection works in both directions.
Adjacency lists are useful for sparse graphs because they store only the existing edges.
Adjacency Matrix Representation
An adjacency matrix represents a graph using a two-dimensional array.
Each row and column represents a vertex. If an edge exists between vertex i and vertex j, the corresponding matrix entry is 1. Otherwise, it is 0.
For example, consider an undirected graph containing these edges:
- A — B
- A — C
- B — D
- C — D
The adjacency matrix is:
| Vertex | A | B | C | D |
|---|---|---|---|---|
| A | 0 | 1 | 1 | 0 |
| B | 1 | 0 | 0 | 1 |
| C | 1 | 0 | 0 | 1 |
| D | 0 | 1 | 1 | 0 |
In this matrix:
-
A to B and B to A both have a value of 1.
-
A to C and C to A both have a value of 1.
-
B to D and D to B both have a value of 1.
-
C to D and D to C both have a value of 1.
The adjacency matrix of a standard undirected graph is symmetric across its main diagonal.
JavaScript Example:
// This program represents an undirected graph using an adjacency matrix.
const vertices = ["A", "B", "C", "D"];
const matrix = [
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]
];
console.log(matrix);
Output:
[
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]
]
An adjacency matrix is useful when the graph is dense or when checking whether an edge exists needs to be performed frequently.
Undirected Graph Implementation in JavaScript
An undirected graph can be implemented using a JavaScript class and a Map data structure.
The following example creates an undirected graph and supports adding vertices, adding edges, and displaying connections.
// This program implements an undirected graph using a JavaScript class.
class UndirectedGraph {
constructor() {
this.adjacencyList = new Map();
}
addVertex(vertex) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}
addEdge(vertex1, vertex2) {
this.addVertex(vertex1);
this.addVertex(vertex2);
this.adjacencyList.get(vertex1).push(vertex2);
this.adjacencyList.get(vertex2).push(vertex1);
}
display() {
for (const [vertex, neighbors] of this.adjacencyList) {
console.log(`${vertex} -> ${neighbors.join(", ")}`);
}
}
}
const graph = new UndirectedGraph();
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "D");
graph.addEdge("C", "D");
graph.display();
Output:
A -> B, C
B -> A, D
C -> A, D
D -> B, C
In this implementation:
- The constructor initializes an empty adjacency list.
- addVertex() adds a new vertex to the graph.
- addEdge() creates a two-way connection between two vertices.
- display() prints each vertex and its adjacent vertices.
This implementation demonstrates how undirected graphs can be created and managed using JavaScript.
Operations on an Undirected Graph
Several operations can be performed on an undirected graph to manage its vertices and connections.
1. Add Vertex: Adds a new vertex to the graph.
2. Add Edge: Creates a connection between two vertices. Both vertices are updated in the adjacency list.
3. Remove Edge: Removes the connection between two vertices. The edge must be removed from both adjacency lists.
4. Remove Vertex: Removes a vertex and all edges connected to it.
5. Search Vertex: Checks whether a particular vertex exists in the graph.
6. Graph Traversal: Visits vertices by following their connections. Two commonly used traversal algorithms are
- Breadth-First Search (BFS).
- Depth-First Search (DFS).
Both algorithms use a visited set to prevent repeatedly visiting the same vertices, especially when cycles exist.
Difference Between Directed and Undirected Graphs
Directed and undirected graphs are two common types of graph data structures. Their main difference is how their edges represent connections.
| Directed Graph | Undirected Graph |
|---|---|
| Edges have a specific direction. | Edges do not have a direction. |
| Connections are one-way unless reverse edges are added. | Connections work in both directions. |
| Edges are represented using arrows. | Edges are represented using simple lines. |
| Indegree and outdegree are used. | Degree is used. |
| The adjacency matrix may be asymmetric. | The adjacency matrix is symmetric for a standard undirected graph. |
| Used in web links and task dependencies. | Used in mutual relationships and two-way connections. |
Applications of Undirected Graphs
Undirected graphs are widely used in computer science and real-world applications where relationships are mutual, or connections work in both directions.
- Social Networking Platforms: Undirected graphs can represent mutual friendships between users. If two users are connected as friends, the relationship is mutual.
- Computer Networks: Undirected graphs can represent network devices connected through two-way communication links.
- Road Networks: Undirected graphs can represent roads that allow travel in both directions between locations.
- Collaboration Networks: Undirected graphs can represent relationships between people who work together on projects or research.
- Electrical Circuits: Undirected graphs can represent components and connections in electrical circuit models when the connections do not have a specified direction.
- Network Design: Undirected graphs are used to design communication and transportation networks. Minimum Spanning Tree algorithms help find a minimum-cost set of connections that links all vertices in a connected weighted undirected graph.
- Recommendation Systems: Undirected graphs can represent mutual relationships between users, products, or interests.
Advantages of Undirected Graphs
Undirected graphs provide several benefits when representing mutual relationships and two-way connections.
- They represent mutual relationships clearly.
- They are easy to understand and implement.
- They support graph traversal algorithms such as BFS and DFS.
- They are useful for modeling social and computer networks.
- They support algorithms such as Minimum Spanning Tree.
- They can efficiently represent connections using adjacency lists.
Disadvantages of Undirected Graphs
Despite their usefulness, undirected graphs also have some limitations.
- They cannot directly represent one-way relationships.
- Large graphs can become difficult to manage.
- Adjacency matrices require significant memory for large sparse graphs.
- Finding paths may require graph traversal algorithms.
- Complex networks may require additional algorithms to analyze connectivity and cycles.
Time and Space Complexity
The complexity of an undirected graph depends on its representation and the operation being performed.
Let:
-
V = Number of vertices.
-
E = Number of undirected edges.
| Operation | Adjacency List | Adjacency Matrix |
|---|---|---|
| Add Vertex | O(1) average | O(V²) if resizing |
| Add Edge | O(1) average | O(1) |
| Check Edge | O(degree) | O(1) |
| Remove Edge | O(degree) | O(1) |
| Space Complexity | O(V + E) | O(V²) |
The adjacency list is generally preferred for sparse graphs because it stores only existing edges.
The adjacency matrix is useful for dense graphs or when checking whether an edge exists needs to be performed quickly.
Common Mistakes to Avoid
-
Treating an undirected edge as one-way: An edge between A and B represents a connection in both directions.
-
Adding an edge to only one adjacency list: When using an adjacency list, both vertices must be updated to maintain the undirected connection.
-
Confusing degree with indegree and outdegree: In an undirected graph, degree counts all edges connected to a vertex.
-
Ignoring cycles during traversal: Always maintain a visited set when implementing BFS or DFS to avoid repeated visits.
-
Choosing an unsuitable graph representation: An adjacency matrix can waste memory for large sparse graphs, while an adjacency list may require more work to check for a particular edge.
Conclusion
An undirected graph is an important data structure used to represent mutual relationships and two-way connections between vertices. It is widely used in social networks, computer networks, road maps, and network design. Understanding its terminology, types, representations, operations, and implementation provides a strong foundation for learning advanced graph algorithms and solving data structure and algorithm problems.
Frequently Asked Questions
1. What is an undirected graph?
An undirected graph is a graph in which edges do not have a specific direction, and connections work in both directions.
2. What is the degree of a vertex in an undirected graph?
The degree of a vertex is the total number of edges connected to that vertex. A self-loop contributes two to the degree.
3. What is the difference between directed and undirected graphs?
A directed graph contains one-way connections, while an undirected graph contains connections that work in both directions.
4. Which representation is commonly used for undirected graphs?
Adjacency lists and adjacency matrices are the two commonly used representations of undirected graphs.
5. Where are undirected graphs used?
Undirected graphs are used in social networks, computer networks, road maps, collaboration systems, and network design.
0 Comments