aboutsummaryrefslogtreecommitdiff
path: root/q2/ford.c
blob: 993a0c3006a0e7da0b9d3e3f0c5f2a22e069e7b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>

int A[10][10], n, d[10], p[10];

int bellman_ford() {
    int i, u, v;
    for (int i = 0; i < n; i++) {
        for (u = 0; u < n; u++) {
            for (v = 0; v < n; v++) {
                if (d[v] > d[u] + A[u][v]) {
                    d[v] = d[u] + A[u][v];
                    p[v] = u;
                }
            }
        }
    }
    for (u = 0; u < n; u++) {
        for (v = 0; v < n; v++) {
            if (d[v] > d[u] + A[u][v]) {
                printf("Detected negative edge\n");
                return -1;
            }
        }
    }
    return 0;
}

int main() {
    scanf("%d", &n);
    int source = 0, destination = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &A[i][j]);
        }
    }
    scanf("%d", &source);
    scanf("%d", &destination);

    printf("Input graph:\n");
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%3d ", A[i][j]);
        }
        printf("\n");
    }

    for (int i = 0; i < n; i++) {
        d[i] = 999;
        p[i] = -1;
    }
    d[source] = 0;
    int valid = bellman_ford();
    if (valid == -1) {
        printf("Graph contains negative edge\n");
        return 0;
    }
    printf("\nFrom Router %d to Router %d\n", source, destination);
    // for(int i=0; i<n; i++){
    //     printf("Cost: %2d | Path: ", d[i]);
    //     if(i != source){
    //         int j = i;
    //         while(p[j] != -1){
    //             printf("%d <- ",j);
    //             j = p[j];
    //         }
    //     }
    //     printf("%d\n",source);
    // }
    printf("Cost: %2d | Path: ", d[destination]);
    if(destination != source){
        int j = destination;
        while(p[j] != -1){
            printf("%d <- ",j);
            j = p[j];
        }
    }
    printf("%d\n",source);
}