DATA STRUCTURES PROGRAM • GRAPHS

Compute Graph Transitive Closure

Learn how to compute graph transitive closure using a clear C program.

AdvancedReachabilityWarshallTransitive closure

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

dsa-transitive-closure.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

1 1 1 1
0 1 1 1
0 0 1 1
0 0 0 1
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Mark a pair reachable when both halves of a path through an intermediate vertex exist.
  3. 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.