DATA STRUCTURES PROGRAM • GRAPHS
Compute Graph Transitive Closure
Learn how to compute graph transitive closure using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int reach[4][4] = {
{1,1,0,0}, {0,1,1,0}, {0,0,1,1}, {0,0,0,1}
};
for (int through = 0; through < 4; through++)
for (int from = 0; from < 4; from++)
for (int to = 0; to < 4; to++)
reach[from][to] = reach[from][to] || (reach[from][through] && reach[through][to]);
for (int row = 0; row < 4; row++) {
for (int column = 0; column < 4; column++) printf("%d ", reach[row][column]);
putchar('\n');
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
1 1 1 1 0 1 1 1 0 0 1 1 0 0 0 1
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Mark a pair reachable when both halves of a path through an intermediate vertex exist.
- Display the computed result.
Mark a pair reachable when both halves of a path through an intermediate vertex exist.
EFFICIENCY
Time and space complexity
Time complexity
O(V³)
Auxiliary space
O(V²)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
