Graphs data structure in C
19 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Match the graph concepts with their descriptions:

Vertex = A node in the graph; can hold data. Edge = A connection between two vertices. Path = A sequence of vertices connected by edges. Cycle = A path that starts and ends at the same vertex.

Match the graph types with their properties:

Directed Graph = Edges have a direction from one vertex to another. Undirected Graph = Edges have no direction (connection is bidirectional). Weighted Graph = Edges have weights (costs) associated with them. Sparse Graph = A graph with relatively few edges compared to the number of vertices.

Match the graph representations with their characteristics:

Adjacency Matrix = A 2D array where matrix[i][j] = 1 if there is an edge from vertex i to vertex j. Adjacency List = An array of lists; each list stores the adjacent vertices for a given vertex. Dense Graph = Most of the possible edges are present. Sparse Graph = Few edges compared to the maximum possible.

Match the space complexity with the correct graph representation method:

<p>O(V^2) = Adjacency Matrix O(V + E) = Adjacency List O(1) = Constant Space O(log V) = Logarithmic Space</p> Signup and view all the answers

Match the following graph representations with their appropriate use cases:

<p>Adjacency Matrix = Suitable for dense graphs where most vertices are connected. Adjacency List = Memory efficient for sparse graphs (graphs with few edges). Graph Traversal = Visiting all nodes in a systematic order (e.g., DFS, BFS). Shortest Path Algorithms = Finding the shortest path between two vertices in a graph (e.g., Dijkstra's algorithm, Bellman-Ford algorithm).</p> Signup and view all the answers

Match the graph representation with its corresponding characteristic:

<p>Adjacency Matrix = Requires $O(V^2)$ space, where V is the number of vertices. Adjacency List = Space efficient for sparse graphs. Edge List = Simple to implement, but less efficient for most graph operations. Incidence Matrix = Requires $O(VE)$ space, where V is the number of vertices and E is the number of edges.</p> Signup and view all the answers

Match each graph traversal algorithm with its primary data structure:

<p>Depth-First Search (DFS) = Stack Breadth-First Search (BFS) = Queue Topological Sort = Stack (in some implementations), often depends on DFS Dijkstra's Algorithm = Priority Queue</p> Signup and view all the answers

Match the graph algorithm with its typical application:

<p>Dijkstra's Algorithm = Finding the shortest path in a weighted graph Prim's Algorithm = Finding the minimum spanning tree in a weighted graph Topological Sort = Task scheduling with dependencies Connected Components = Network analysis to identify clusters of connected nodes</p> Signup and view all the answers

Match the graph application with its real-world example:

<p>Social Network = Representing friendships between users on a social media platform Mapping = Representing roads and intersections for navigation systems Recommendation System = Suggesting products to customers based on their purchase history Network Routing = Determining the optimal path for data packets on the internet</p> Signup and view all the answers

Match the following graph concepts with their definitions:

<p>Directed Graph = A graph where edges have a direction, indicating a one-way relationship Undirected Graph = A graph where edges have no direction, indicating a two-way relationship Weighted Graph = A graph where edges have weights assigned to them, representing a cost or distance. Acyclic Graph = A graph that contains no cycles.</p> Signup and view all the answers

Match the time complexity with the corresponding graph algorithm (using Adjacency Matrix):

<p>Depth-First Search (DFS) = $O(V^2)$ Breadth-First Search (BFS) = $O(V^2)$ Dijkstra's Algorithm (basic implementation) = $O(V^2)$ Prim's Algorithm (basic implementation) = $O(V^2)$</p> Signup and view all the answers

Match the time complexity with the corresponding graph algorithm (using Adjacency List):

<p>Depth-First Search (DFS) = $O(V+E)$ Breadth-First Search (BFS) = $O(V+E)$ Dijkstra's Algorithm (with priority queue) = $O(E log V)$ Prim's Algorithm (with priority queue) = $O(E log V)$</p> Signup and view all the answers

Match the graph property with its implication:

<p>Dense Graph = Adjacency matrix is often preferred due to its efficient random access. Sparse Graph = Adjacency list is often preferred for its space efficiency. Weighted Edges = Requires algorithms like Dijkstra's or Bellman-Ford for shortest path calculations. Cyclic Graph = May require cycle detection algorithms, like finding strongly connected components.</p> Signup and view all the answers

Match the following C code snippets with their function related to graph representation (using Adjacency Matrix):

<p><code>adjMatrix[u][v] = 1;</code> = Adds an edge between vertices u and v. <code>adjMatrix[i][j] = 0;</code> = Initializes the adjacency matrix by setting all edge weights to 0. <code>if (adjMatrix[v][i] == 1 &amp;&amp; !visited[i])</code> = Checks if there is an edge between vertex <code>v</code> and vertex <code>i</code>, and if vertex <code>i</code> has not been visited during traversal. <code>printf(&quot;%d &quot;, adjMatrix[i][j]);</code> = Prints the element at position [i][j] in the adjacency matrix.</p> Signup and view all the answers

Match the following C code snippets with their function related to graph representation (using Adjacency Lists):

<p><code>newNode-&gt;next = graph-&gt;array[src].head;</code> = Adds a new node to the head of the adjacency list for vertex src. <code>struct AdjListNode* pCrawl = graph-&gt;array[v].head;</code> = Initializes a pointer <code>pCrawl</code> to traverse the adjacency list of vertex <code>v</code>. <code>printf(&quot;-&gt; %d&quot;, pCrawl-&gt;dest);</code> = Prints the destination vertex of the current node in the adjacency list. <code>graph-&gt;array[i].head = NULL;</code> = Initializes the adjacency list for vertex <code>i</code> to be empty.</p> Signup and view all the answers

Match the C code action with the corresponding step in Breadth-First Search (BFS):

<p><code>enqueue(startVertex);</code> = Adds the starting vertex to the queue. <code>int currentVertex = dequeue();</code> = Removes and retrieves the vertex at the front of the queue. <code>visited[currentVertex][i] == 1 &amp;&amp; !visited[i]</code> = Checks if an adjacent vertex has been visited. <code>visited[startVertex] = 1;</code> = Marks the starting vertex as visited.</p> Signup and view all the answers

Pair the pseudocode step with its corresponding graph algorithm:

<p>Visit the adjacent unvisited vertex. Mark it as visited. Display it. Add it to a queue. = Breadth-First Search (BFS) Visit the adjacent unvisited vertex. Mark it as visited. Display it. = Depth-First Search (DFS) Select the edge with the smallest weight. Add it to the spanning tree if it doesn't form a cycle. = Kruskal's Algorithm Select the vertex with the smallest known distance from the source. Update the distances of its neighbors. = Dijkstra's Algorithm</p> Signup and view all the answers

Match the concept with its application in graph algorithms:

<p>Relaxation = Process of repeatedly decreasing the estimate of the shortest path until the optimal value is reached in shortest path algorithms. Topological Ordering = Linear ordering of vertices in a directed acyclic graph (DAG) where for every directed edge uv, vertex u comes before vertex v in the ordering. Cycle Detection = Determining if a graph contains cycles, important for algorithms like topological sort (which only works on DAGs). Spanning Tree = A subgraph that connects all vertices together, without any cycles and with the minimum possible number of edges.</p> Signup and view all the answers

Match the graph problem with the appropriate algorithm to solve it:

<p>Finding the shortest path from one node to all other nodes in a weighted graph with non-negative edge weights. = Dijkstra's Algorithm Finding the shortest path from one node to all other nodes in a weighted graph with possible negative edge weights, but no negative cycles. = Bellman-Ford Algorithm Finding the minimum cost to connect all nodes in a weighted graph. = Prim's or Kruskal's Algorithm Determining an order to process tasks with dependencies. = Topological Sort</p> Signup and view all the answers

Flashcards

What is a Graph?

A non-linear data structure of nodes (vertices) connected by links (edges).

What is a Vertex?

A node in a graph that can hold data.

What is an Edge?

A connection between two vertices. It may have a direction.

What is an Adjacency Matrix?

2D array indicating the presence (or weight) of edges between vertices.

Signup and view all the flashcards

What is an Adjacency List?

An array of lists where each list stores the adjacent vertices for a given vertex.

Signup and view all the flashcards

Adjacency Matrix

A 2D array where rows and columns represent vertices, and values indicate the presence of an edge.

Signup and view all the flashcards

Adjacency List

Each vertex has a list of adjacent vertices stored as linked lists.

Signup and view all the flashcards

Depth-First Search (DFS)

Explores deeply along each branch before backtracking.

Signup and view all the flashcards

Breadth-First Search (BFS)

Explores all neighbors at the present depth prior to moving on to the nodes at the next depth level.

Signup and view all the flashcards

DFS Algorithm Steps

Mark the current vertex as visited, explore each adjacent unvisited vertex using DFS recursively.

Signup and view all the flashcards

BFS Algorithm Steps

Start at a vertex, enqueue it, then while the queue isn't empty, dequeue a vertex, mark it visited, and enqueue its unvisited neighbors.

Signup and view all the flashcards

Social Network Graphs

Representing relationships, such as friends.

Signup and view all the flashcards

Mapping Graphs

Representing roads and routes.

Signup and view all the flashcards

Recommendation System Graphs

Suggesting items based on preferences.

Signup and view all the flashcards

Network Routing Graphs

Finding optimal paths between points.

Signup and view all the flashcards

Scheduling Graphs

Representing tasks and their dependencies.

Signup and view all the flashcards

Shortest Path Algorithms

Finds the shortest path between two vertices.

Signup and view all the flashcards

Minimum Spanning Tree Algorithms

Finds a minimum spanning tree for a connected, weighted graph.

Signup and view all the flashcards

Topological Sort

Orders vertices such that for every edge from A to B, A comes before B.

Signup and view all the flashcards

Connected Components

Identifying sets of reachable vertices.

Signup and view all the flashcards

Study Notes

  • Graphs are non-linear data structures consisting of nodes (vertices) and connections between them (edges)
  • They are used to represent relationships or networks
  • C can be used to implement graphs

Basic Concepts

  • Vertex: A node in the graph which can hold data
  • Edge: A connection between two vertices that can be directed or undirected
  • Directed Graph: Edges possessing direction from one vertex to another
  • Undirected Graph: Edges lacking direction, thus the connection is bidirectional
  • Weighted Graph: Edges possessing weights or costs
  • Path: A sequence of vertices connected by edges
  • Cycle: A path that starts and ends at the same vertex
  • Adjacency: Indicates two vertices are connected by an edge

Graph Representation

  • Adjacency Matrix: A 2D array where matrix[i][j] = 1 if an edge exists from vertex i to vertex j; otherwise, it's 0; for weighted graphs, matrix[i][j] stores the weight of the edge
  • Adjacency List: An array of lists where each array element represents a vertex, and the list contains the adjacent vertices

Adjacency Matrix Implementation in C

  • Requires a two-dimensional array
  • For a graph with 'V' vertices, the matrix is of size V x V
  • Suitable for dense graphs where most vertices are connected
  • O(V^2) is the space complexity

Adjacency List Implementation in C

  • Requires an array of linked lists
  • Each linked list stores the adjacent vertices for a given vertex
  • Memory efficient for sparse graphs (graphs with few edges)
  • O(V + E) is the space complexity, where E is the number of edges

C Code Example: Adjacency Matrix

 #include <stdio.h>
 #include <stdlib.h>

 #define V 5 /* Number of vertices */

 /* Function to initialize the adjacency matrix */
 void initMatrix(int adjMatrix[][V]) {
  int i, j;
  for (i = 0; i < V; i++)
  for (j = 0; j < V; j++)
  adjMatrix[i][j] = 0;
 }

 /* Function to add an edge to the graph */
 void addEdge(int adjMatrix[][V], int u, int v) {
  adjMatrix[u][v] = 1;
  adjMatrix[v][u] = 1; /* For undirected graph */
 }

 /* Function to print the adjacency matrix */
 void printMatrix(int adjMatrix[][V]) {
  int i, j;
  for (i = 0; i < V; i++) {
  printf("Vertex %d: ", i);
  for (j = 0; j < V; j++)
  printf("%d ", adjMatrix[i][j]);
  printf("\n");
  }
 }

 int main() {
  int adjMatrix[V][V];

  initMatrix(adjMatrix);

  addEdge(adjMatrix, 0, 1);
  addEdge(adjMatrix, 0, 4);
  addEdge(adjMatrix, 1, 2);
  addEdge(adjMatrix, 1, 3);
  addEdge(adjMatrix, 1, 4);
  addEdge(adjMatrix, 2, 3);
  addEdge(adjMatrix, 3, 4);

  printMatrix(adjMatrix);

  return 0;
 }

C Code Example: Adjacency List

 #include <stdio.h>
 #include <stdlib.h>

 /* Structure for an adjacency list node */
 struct AdjListNode {
  int dest;
  struct AdjListNode* next;
 };

 /* Structure for an adjacency list */
 struct AdjList {
  struct AdjListNode* head;
 };

 /* Structure for a graph */
 struct Graph {
  int V; /* Number of vertices */
  struct AdjList* array;
 };

 /* Function to create a new adjacency list node */
 struct AdjListNode* newAdjListNode(int dest) {
  struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
  newNode->dest = dest;
  newNode->next = NULL;
  return newNode;
 }

 /* Function to create a graph */
 struct Graph* createGraph(int V) {
  struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
  graph->V = V;
  graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));
  int i;
  for (i = 0; i < V; i++)
  graph->array[i].head = NULL;
  return graph;
 }

 /* Function to add an edge to the graph */
 void addEdge(struct Graph* graph, int src, int dest) {
  struct AdjListNode* newNode = newAdjListNode(dest);
  newNode->next = graph->array[src].head;
  graph->array[src].head = newNode;

  /* For undirected graph, add an edge from dest to src also */
  newNode = newAdjListNode(src);
  newNode->next = graph->array[dest].head;
  graph->array[dest].head = newNode;
 }

 /* Function to print the graph */
 void printGraph(struct Graph* graph) {
  int v;
  for (v = 0; v < graph->V; v++) {
  struct AdjListNode* pCrawl = graph->array[v].head;
  printf("Adjacency list of vertex %d\n head ", v);
  while (pCrawl) {
  printf("-> %d", pCrawl->dest);
  pCrawl = pCrawl->next;
  }
  printf("\n");
  }
 }

 int main() {
  int V = 5;
  struct Graph* graph = createGraph(V);
  addEdge(graph, 0, 1);
  addEdge(graph, 0, 4);
  addEdge(graph, 1, 2);
  addEdge(graph, 1, 3);
  addEdge(graph, 1, 4);
  addEdge(graph, 2, 3);
  addEdge(graph, 3, 4);

  printGraph(graph);

  return 0;
 }

Graph Traversal

  • Depth-First Search (DFS): Explores as far as possible along each branch before backtracking and uses a stack (implicitly through recursion)
  • Breadth-First Search (BFS): Explores all the neighbors of a node before moving to the next level of neighbors and uses a queue

Depth-First Search (DFS)

  • Algorithm:
  • Start at a vertex
  • Mark the vertex as visited
  • Recursively call DFS for each adjacent unvisited vertex

Breadth-First Search (BFS)

  • Algorithm:
  • Start at a vertex
  • Enqueue the vertex
  • While the queue is not empty:
  • Dequeue a vertex
  • Mark the vertex as visited
  • Enqueue all unvisited adjacent vertices

C Code Example: DFS

 #include <stdio.h>
 #include <stdlib.h>

 #define V 5

 int adjMatrix[V][V];
 int visited[V];

 void initMatrix() {
  int i, j;
  for (i = 0; i < V; i++) {
  for (j = 0; j < V; j++) {
  adjMatrix[i][j] = 0;
  }
  visited[i] = 0;
  }
 }

 void addEdge(int u, int v) {
  adjMatrix[u][v] = 1;
  adjMatrix[v][u] = 1;
 }

 void DFS(int v) {
  visited[v] = 1;
  printf("%d ", v);

  for (int i = 0; i < V; i++) {
  if (adjMatrix[v][i] == 1 && !visited[i]) {
  DFS(i);
  }
  }
 }

 int main() {
  initMatrix();
  addEdge(0, 1);
  addEdge(0, 2);
  addEdge(1, 3);
  addEdge(2, 4);

  printf("DFS traversal starting from vertex 0: ");
  DFS(0);
  printf("\n");

  return 0;
 }

C Code Example: BFS

 #include <stdio.h>
 #include <stdlib.h>

 #define V 5

 int adjMatrix[V][V];
 int visited[V];
 int queue[V];
 int front = 0, rear = 0;

 void initMatrix() {
  int i, j;
  for (i = 0; i < V; i++) {
  for (j = 0; j < V; j++) {
  adjMatrix[i][j] = 0;
  }
  visited[i] = 0;
  }
  front = rear = 0;
 }

 void addEdge(int u, int v) {
  adjMatrix[u][v] = 1;
  adjMatrix[v][u] = 1;
 }

 void enqueue(int v) {
  queue[rear++] = v;
 }

 int dequeue() {
  return queue[front++];
 }

 int isEmpty() {
  return front == rear;
 }

 void BFS(int startVertex) {
  visited[startVertex] = 1;
  enqueue(startVertex);

  while (!isEmpty()) {
  int currentVertex = dequeue();
  printf("%d ", currentVertex);

  for (int i = 0; i < V; i++) {
  if (adjMatrix[currentVertex][i] == 1 && !visited[i]) {
  visited[i] = 1;
  enqueue(i);
  }
  }
  }
 }

 int main() {
  initMatrix();
  addEdge(0, 1);
  addEdge(0, 2);
  addEdge(1, 3);
  addEdge(2, 4);

  printf("BFS traversal starting from vertex 0: ");
  BFS(0);
  printf("\n");

  return 0;
 }

Applications of Graphs

  • Social networks: Representing relationships between users
  • Mapping: Representing road networks
  • Recommendation systems: Suggesting items based on user preferences
  • Network routing: Finding the shortest path between two points in a network
  • Scheduling: Representing tasks and their dependencies

Common Graph Algorithms

  • Shortest Path Algorithms: Dijkstra's algorithm and Bellman-Ford algorithm find the shortest path between two vertices
  • Minimum Spanning Tree Algorithms: Prim's algorithm and Kruskal's algorithm find a minimum spanning tree for a connected, weighted graph
  • Topological Sort: Orders the vertices in a directed acyclic graph (DAG) such that for every directed edge from vertex A to vertex B, vertex A comes before vertex B in the ordering
  • Connected Components: Identifying sets of vertices that are reachable from each other

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Description

Explore graphs, a non-linear data structure consisting of nodes and edges. Learn about vertices, edges, directed vs undirected graphs, and weighted graphs. Discover graph representations using Adjacency Matrix and Adjacency List.

More Like This

Graphs and Data Structures Quiz
15 questions

Graphs and Data Structures Quiz

ChivalrousSmokyQuartz avatar
ChivalrousSmokyQuartz
Graphs in Data Structures
5 questions
Use Quizgecko on...
Browser
Browser