c programming - exercise c

Download C Programming - Exercise C

If you can't read please download the document

Upload: theo

Post on 09-Nov-2015

11 views

Category:

Documents


5 download

DESCRIPTION

C Programming - Exercise C

TRANSCRIPT

//Exercise C#include #include #define N 5int path(int start, int end); //Finds the min path and computes its costint connection[N][N-1] = {0}, weight[N][N-1] = {0};int seq[5] = {0}, c = 0;int main (void) {int i = 0, j = 0, t = 0, f = -1, l = -1, minWeight;//Input of connection and weightfor (; i < N; i++) {printf("How many tops are connected with top %d? ", i);scanf(" %d", &t);if(t)printf("Type them followed by their weights separated with spaces: ");for (j = 0; j < t; j++) {scanf(" %d", &connection[i][j]);scanf(" %d", &weight[i][j]);}for(j = 0; j < t; j++) {while(connection[i][j] < 0 || connection[i][j] >= N) {printf("Top %d does not exist. Please type it again (alone): ", connection[i][j]);scanf(" %d", &connection[i][j]);}}for(; j < N-1; j++) {connection[i][j] = -1000;weight[i][j] = 1000;}}printf("Which is the first top and which the last one? ");scanf(" %d %d", &f, &l);while(f < 0 || f >= N || l < 0 || l >= N) {printf("Not valid tops. Please type them again: ");scanf(" %d %d", &f, &l);}minWeight = path(f, l);printf("\n\nThe path from %d to %d is (", f, l);for (i = 0; i < c; i++)printf("%d, ", seq[i]);printf("\b) with cost %d.\n\n", minWeight);return 0;}int path(int s, int e) {int i = 0, j =0, minW = 999, next = -1;if (s == e) {seq[c++] = s;return 0;}for (; j < N-1; j++)if (connection[s][j] >= 0 && weight[s][j] < minW) {minW = weight[s][j];next = connection[s][j];}for (; i < N; i++)for (j = 0; j < N-1; j++)if (connection[i][j] == s) {connection[i][j] = -1;}seq[c++] = s;if (next == -1) {printf("\nThere is no path!\n\n");exit(0);} elsereturn minW + path(next, e);}