Warshall algorithm (transitive closure)

Description of Warshall

I do not wanna describe the specific principle of the Warshall, I just would like to use a simple example to demonstrate the working function of the Warshall.

Simple example

I assume an array named M with the size of 4*4. 4 is the number of row and 4 is the number of colume.

 

step1: Look at the colume 1 of M, M(3,1)=1 and M(4,1)=1. So we will add the row 1 to the row 3 and row 4 seperately. [Noted: 1+1=1]

 

step2: Look at the colume 2 of M, M(1,2)=1, M(3,2)=1 and M(4,2)=1. So we will add the row 2 to the row 1, row 3 and row 4 seperately.

step3: Look at the colume 3 of M, M(1,3)=1, M(2,2)=1, M(3,2)=1 and M(4,2)=1. So we will add the row 3 to the row 1, row 2, row 3 and row 4 seperately.

 

step4: Look at the colume 4 of M, M(1,4)=1, M(2,4)=1, M(3,4)=1 and M(4,4)=1. So we will add the row 4 to the row 1, row 2, row 3 and row 4 seperately.

 

Implementation Code

#include <stdio.h>
#define N 4  
int get_matrix(int a[N][N])
{
    int i = 0,j = 0;
    for (i = 0;i < N;i++) 
    {
        for (j = 0;j < N;j++)
         {
            scanf("%d",&a[i][j]);
            if (a[i][j] != 0 && a[i][j] != 1)
                return 1;            
         }
    }
    return 0;
}
int output_matrix(int a[N][N])
{
    int i = 0,j = 0;
    for (i = 0;i < N;i++) {
        for (j = 0;j < N;j++) {
            printf("%d  ",a[i][j]);
        }
        putchar('\n');
    }
}
int warshall(int a[][N])
{   
    int i = 0;
    int j = 0;
    int k = 0;
    for (i = 0;i < N;i++) 
    {                  
        for (j = 0;j < N;j++) 
        {
            if (a[j][i]) 
            {
                for (k = 0;k < N;k++) 
                {
                    a[j][k] = a[j][k] | a[i][k];
                }
            } 
        }
    }
}
int main()
{
    int a[N][N] = {0};
    printf("please input a matrix with %d * %d:\n",N,N);
    if (get_matrix(a))
     {  printf("Get matrix error!Only 0 or 1 in matrix!\n");
        return 1; //错误返回主函数,返回值为1; 
     }
    warshall(a);
    output_matrix(a);

    return 0;//正常返回主函数,返回值为0; 
}

Guess you like

Origin blog.csdn.net/qq_55126913/article/details/130516522