Scanning numbers from a file into a two dimentional array - c

I am new to programming so I apologize if I mess up on anything.
So I am trying to scan a file with multiple lines of numbers and put them into a two dimensional array. I've tried looking at other questions relating to this and nothing has worked so far.
So I have tried using nested loops to scan the array and put the numbers inside but nothing seems to happen.
Inside the txt file is as follows:
0 7 9 4 0 0 8 0 4 5 0 1
0 2 4 0 0 0 1 6 2 8 6 0
0 1 1 1 1 0 8 5 6 8 0 7
0 5 1 0 0 0 1 3 8 1 0 1
Every 12th number is a new line.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void
barcodeArray(int barcode[ROW][COL])
{
char buffer[BUF_SIZE];
FILE* f = fopen("q5_input.txt","r");
if(f == NULL)
{
printf("no such file.");
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
fscanf(f, "%1d", &barcode[k][j]);
printf("%ls", &barcode[k][j]);
}
}
fclose(f);
}
int
main(void)
{
int barcode[ROW][COL];
barcodeArray;
}
The printf inside the for loops is just reading back the numbers as it inputs the numbers in the array. As the code is it compiles but does nothing.

You must call your function with argument barcodeArray(barcode);
Edit : If you are not sure of the size of the array you can take a look at dynamically allocated variables. This is an important part of C programming

Try this way. I think using freopen() is easier and hassle free. It enables you to use same I/O functions that you use for console I/O operations.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void barcodeArray()
{
int barcode[ROW][COL];//This can be declared inside the function.
char buffer[BUF_SIZE];
FILE* f=freopen("q5_input.txt","r",stdin);
if(f == NULL)
{
printf("no such file.\n");
return;
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
scanf("%d",&barcode[k][j]);
printf("%d ",barcode[k][j]);
}
printf("\n");
}
fclose(f);
}
int main(void)
{
barcodeArray();
}
Additionally if you want to output it in a file you can do the following in the main function:
int main(void)
{
freopen("out.txt","w",stdout);
barcodeArray();
}

Related

How complete a matrix with the information of a file in C?

I'm learning C, but I have a problem with an exercise. I need to fill a matrix that I started with zeros, with the information of a file. The file contains some coordinates and I need to put in the matrix the numbers that contain the file, but in the row of coordinates previous to which the file gives me.
For example, if I have this file:
2,3 4 3 1
3,1 3 2 2
1,4 1 2 8
I need my final matrix to look like this:
0 0 0 1 2 8
0 0 4 3 1 0
3 2 2 0 0 0
0 0 0 0 0 0
My code: (that only opens the file and creates the matrix because I'm looking for information or examples, but I can not find anything useful)
#include <stdio.h>
int main(){
FILE *data;
data = fopen("example.txt","r");
if (data == NULL)
{
printf("\nERROR\n");
return -1;
}
int row = 4;
int col = 6;
int matrix[row][col];
for (int x = 0; x < row; ++x)
{
for (int y = 0; y < col; ++y)
{
matrix[x][y]=0;
}
}
fclose(data);
for (int x = 0; x < row; ++x)
{
for (int y = 0; y < col; ++y)
{
printf("[%d]",matrix[x][y]);
}
printf("\n");
}
return 0;
}
There are many, many ways to do this. If you know you will have 2 coordinates and 3 values per-line, then one of the easiest, and most robust ways of handling the read and parsing the data from each line, is to read each line into a buffer with fgets and then parse the line into the individual coordinates with sscanf.1 While you could accomplish the same thing with a single call to fscanf, reading with fgets will insure you consume an entire line of data each time and allows independent validation of your (1) read of data from the file; and (2) the parsing of the data into your coordinates and values.
You then simply need to map your coordinates into valid C-indexes by subtracting 1 (remember arrays in C a zero-based not one-based), check to make sure your coordinates are valid so that writing 3 values beginning at your indexes do not write beyond the bounds of your array, and finally, loop writing your 3-values to the x row beginning at the y index.
A simple implementation could be:
#include <stdio.h>
#define NVAL 3 /* if you need a constant, #define one (or more) */
#define ROW 4
#define COL 6
#define MAXC 1024
int main (int argc, char **argv) {
char buf[MAXC]; /* buffer to hold each line read with fgets */
int matrix[ROW][COL] = {{0}}; /* 2D array initialized all zero */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
while (fgets (buf, MAXC, fp)) { /* read each line into buf */
int x, y, data[NVAL] = {0}; /* declare coords/data vars */
if (sscanf (buf, "%d,%d %d %d %d", /* parse line into values */
&x, &y, &data[0], &data[1], &data[2]) != 5) {
fputs ("error: invalid line format.\n", stderr);
continue; /* skip to next line on error */
}
x = x - 1; /* convert coords to zero based index for C */
y = y - 1;
if (x < ROW && y <= COL - NVAL) { /* check valid indexes */
for (int i = 0; i < NVAL; i++) /* loop over each value */
matrix[x][y++] = data[i]; /* write numbers to array */
}
}
if (fp != stdin) fclose (fp); /* close file if not stdin */
for (int i = 0; i < ROW; i++) { /* loop over rows */
for (int j = 0; j < COL; j++) /* loop over cols */
printf ("%2d", matrix[i][j]); /* outputting values */
putchar ('\n'); /* tidy up with newline */
}
return 0;
}
Example Input File
$ cat dat/matcoords.txt
2,3 4 3 1
3,1 3 2 2
1,4 1 2 8
Example Use/Output
$ ./bin/matrix_data_at_coords <dat/matcoords.txt
0 0 0 1 2 8
0 0 4 3 1 0
3 2 2 0 0 0
0 0 0 0 0 0
Look things over and let me know if you have further questions.
footnotes:
1. Note: none of the scanf family provide any error reporting capability beyond succeed/fail. For fine-grained error reporting for numeric conversion, use the strtoX family of functions (e.g. strtol, strtoul, strtod, etc...)
Try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
char string[99];
FILE *data;
int row = 4;
int col = 6;
int y=0;
int matrix[row][col];
int matrixrow,position, s1 , s2 , s3 ;
for (int x = 0; x < row; ++x)
{
for (int y = 0; y < col; ++y)
{
matrix[x][y]=0;
}
}
data=fopen("example.txt" ,"r");
while( fgets( string , 10 , data))
{
// each row we expect int comma int space int space int space int space
// first int is row , int after comma is position , next 3 ints are data to stuff at position
matrixrow =(string[0]- '0')-1; // substract 0 to get int
position=(string[2]- '0')-2;
s1=string[4]- '0';
s2=string[6]- '0';
s3=string[8]- '0';
matrix[matrixrow][position+1]=s1;
matrix[matrixrow][position+2]=s2;
matrix[matrixrow][position+3]=s3;
printf("\n\nfrom text file matrix");
printf("\n%s", string);
printf("\noutput");
printf("[%d]", matrixrow);
for( y=0 ; y<col-1 ; y++)
printf("[%d]", matrix[matrixrow][y]);
}
printf("\n\nPrint whole matrix\n" );
for (int x = 0; x < row; ++x)
{
for (int y = 0; y < col; ++y)
{
printf("[%d]",matrix[x][y]);
}
printf("\n");
}
fclose(data);
}

C - Reading Till The EOF, Getting Additional Addresses and Numbers (Array)

So, I have a File full of numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
The case is, I don't know the exact number of numbers in this file, so I don't know the exact size of array I will need to write this file info in to this array.
I just gave array much bigger size than I need and I will show you the output, partially it does its job.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#define ARR_SIZE 30
int main(void){
FILE *fp;
int array[ARR_SIZE];
fp = fopen("C:/project/project.txt", "r");
printf("Numbers: ");
for(int i = 0; i < ARR_SIZE; i++){
fscanf(fp, "%d", &array[i]);
}
for(int j = 0; j < ARR_SIZE; j++){
printf("\n%d", array[j]);
}
fclose(fp);
return 0;
}
I am just trying to do standard things, opening file, reading file with for loop, writing all this info to array and outputting array.
Here is the output I get, I understand it is because of the size, but can you tell me how to limit all of these? Easiest way?
Output:
Numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4199136
0
4200896
6422240
6422296
6422476
1998244384
592257989
-2
1998220218
1998220461
4200896
6422368
4200987
4200896
I have array size 30 and numbers in the file 15, first 15 is okay, it is exactly what I need, but I don't need those number after it...
You need a stop-condition for the loop that reads from the file. One option is to stop when you can't scan an item. Use the return value from fscanf to detect that.
When you do the printing only print the number of items actual scan'ed.
Try
for(int i = 0; i < ARR_SIZE; i++){
if (fscanf(fp, "%d", &array[i]) != 1) break; // Stop if the scan fails
}
for(int j = 0; j < i; j++){ // ARR_SIZE replaced by i
printf("\n%d", array[j]);
}
BTW: You should check that fp is valid just after the file open.

Value changing error of the array's first element when passed to a method in C

I have created one array, got input from the user, and passed that array into a method.
After passing it, the value of first element changes and I can't understand why and how.
For instance:
I enter 55 1 2 6 7 5 4 0 displays 70 1 2 6 7 5 4.
Similarly, 121 5 6 1 2 0 displays 26227 5 6 1 2.
int main(int argc, char *argv[]) {
int sequence[100];
int i;
int sequenceSize =0;
for(i =0; i < 100; i++){
scanf("%d",&sequence[i]);
if(sequence[i] == 0){
break;
}
sequenceSize++;
}
method(sequence, sequenceSize);
return 0;
}
void method( int A[] , int sequenceSize){
int M;
printf("This is the array \n");
for(M = 0; M < sequenceSize; M++){
printf("%d ", A[M]);
}
}
I believe it's a problem of your IDE. Clean your project before running.
You can test your program here
https://www.onlinegdb.com/online_c_compiler

How to scanning lines, each line differently, in c?

Lets say i have this text file for example:
4
1 2 3 4
3 9 8 7
1 1 2 1
8 7 8 6
I want to store the first line ("4") to one variable, and the other lines,
insert them to 2d matrix as the way they showing (dynamic 2d array).
Notice that its just example, i just know that the first line is one char, and i don't know the len of the rest of the lines except that are N*N matrix.
How can i do this in C?
Edited: so the matrix should only have numbers, so sor example this txt file:
4
1 2 3 4
3 9 8 7
1 W 2 1
8 7 8 6 is illegal . how can i handle this?
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp = fopen("data.txt", "r");
int n;
fscanf(fp, "%d", &n);
int (*mat)[n] = malloc(sizeof(int[n][n]));
int *p = &mat[0][0];
while(p < &mat[n-1][n])
fscanf(fp, "%d", p++);
fclose(fp);
//check
for(int r=0; r < n; ++r){
for(int c=0; c < n; ++c)
printf("%d ", mat[r][c]);
printf("\n");
}
free(mat);
return 0;
}

Floyd-Warshall algorithm not finding length of shortest paths correctly

This is probably a bad question to ask on SO since my rep is so low, but I have been looking through other solutions for hours, and my code seems nearly identical to the working solutions that I've come across. Please do not ignore the question based on low rep.
The output matrix, d[][] contains the (incorrect) lengths of the shortest paths between a given pair of vertices. The solution provided in the networkx library for Python has been used.
As an excerpt, the results for n=20 have been provided. I'm not printing out the paths greater than infinity (i.e. 99999), since there is overflow.
This is what the graph looks like:
My Floyd-Warshall algorithm implementation (C)
20 0 2
20 1 6
20 2 9
20 3 9
20 4 8
20 5 10
20 7 2
20 8 7
20 9 10
20 11 5
20 12 2
20 13 7
20 14 6
20 15 17
20 17 4
20 18 5
Networkx solution to Floyd-Warshall algorithm (Python)
20 0 2
20 1 5
20 2 4
20 3 4
20 4 3
20 5 7
20 7 2
20 8 2
20 9 4
20 11 4
20 12 2
20 13 6
20 14 5
20 15 4
20 17 3
20 18 4
20 20 0
Implementation:
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define INF 9999
#define min(a,b) (a>b)?b:a;
int n;
/*
* Method signatures
*/
void shortestPath(int matrix[][n]);
int main(){
char buf[16], c;
int i, j, weight, ret;
/* Open file handler for file containing test data */
FILE *file = fopen("eg2.txt", "r");
if(file==NULL){
puts("I/O error: cannot read input file");
fclose(file);
exit(1);
}
/* Get number of vertices in file */
fscanf(file, "%d", &n);
/* Initialise matrix of n*3 elements */
int matrix[n][n];
memset(matrix, INF, n*n*sizeof(int));
while((ret = fscanf(file, "%d %d %d", &i, &j, &weight)) != EOF) {
if(ret == 3){
matrix[i][j]=weight;
} else {
printf("ERROR: retrieved %d values (expecting 3)\n", ret);
break;
}
}
fclose(file);
/* Output matrix */
for(i=0; i<n; i++){
matrix[i][i]=0;
for(j=0; j<n; j++){
printf("%d ", matrix[i][j]);
}
printf("\n");
}
shortestPath(matrix);
}
/*
* Implementation of the Floyd-Warshall path finding algorithm
*/
void shortestPath(int matrix[][n]){
int d[n][n], k, i, j;
/* Copy values from matrix[][] to d[][] */
for(i=0; i<n; i++){
for(j=0; j<n; j++){
d[i][j] = matrix[i][j];
}
}
for(k=0; k<n; k++){
for(i=0; i<n; i++){
for(j=0; j<n; j++){
if (d[i][k] + d[k][j] < d[i][j]){
d[i][j] = d[i][k] + d[k][j];
}
}
}
}
for(i=0; i<n; i++){
for(j=0; j<n; j++){
if((d[i][j]!=0)&&(d[i][j]<INF)){
printf("%d\t%d\t%d\n", i, j, d[i][j]);
}
}
}
}
Test client (Python)
#!/usr/bin/python2.7
try:
import matplotlib.pyplot as plt
from collections import defaultdict
import networkx as nx
import numpy as np
except:
raise
nodes = defaultdict(dict)
with open('eg2.txt', 'r') as infile:
for line in infile.readlines()[1:]:
line = map(int, line.split())
src = line[0]
dst = line[1]
weight = line[2]
nodes[src][dst]=weight
G = nx.Graph()
for i in nodes:
for j in nodes[i]:
G.add_edge(i, j, weight=nodes[i][j])
rs = nx.floyd_warshall(G)
for i in rs:
for j in rs[i]:
print "%d\t%d\t%d" % (i, j, rs[i][j])
pos = nx.shell_layout(G)
nx.draw(G, pos, node_size=500, node_color='orange', edge_color='blue', width=1)
plt.axis('off')
plt.show()
Don't use dynamically sized arrays (e.g. non-constant n in the array size), they may not work the way you think. One simple way to fix your code:
#define MAXN 100
int n;
...
int matrix[MAXN][MAXN];
scanf("%d", &n);
if (n < 1 || n > MAXN) abort();
...
void shortestPath(int matrix[][MAXN]) {
Please recompile your code with all warnings enabled (e.g. gcc -W -Wall -Wextra -ansi), fix all the warnings, and indicate in the question that your code compiles without emitting any warning.
Here is a complete solution for you. I used #pts's suggestion of using a fixed array, and the suggestion from the comments of initializing the array explicitly with a pair of nested loops. I also took some liberties with the way the algorithm works - for example, with the option to have either directed or undirected graphs - and show how you can include some intermediate outputs to help in the debugging.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INF 9999
#define MIN(a,b)((a)<(b))?(a):(b)
// uncomment the next line to make processing symmetrical
// i.e. undirected edges
// #define SYM
#define NMAX 20
int n;
void shortestPath(int m[NMAX][NMAX]);
void printMatrix(int m[NMAX][NMAX]);
// implementation of floyd-warshall algorithm
// with minimal error checking
// input file = series of nodes on graph in form
// start, end, length
// algorithm attempts to find shortest path between any connected nodes
// by repeatedly looking for an intermediate node that shortens the current distance
// graphs are directional - 3 4 5 does not imply 4 3 5
// this can be changed by uncommenting the #define SYM line above
// also, hard coded to have no more than 20 nodes - defined with NMAX above
// path to input file is hard coded as "eg2.txt"
int main(void) {
int i, j, weight, ret;
// open input file:
FILE *fp = fopen("eg2.txt", "r");
if(fp == NULL) {
printf("cannot read input file\n");
exit(1);
}
// read number of nodes in the graph:
fscanf(fp, "%d", &n);
if(n > NMAX) {
printf("input too large\n");
fclose(fp);
exit(1);
}
printf("n is %d\n", n);
// generate matrix:
int matrix[NMAX][NMAX];
for(i=0; i<NMAX;i++)
for(j=0; j<NMAX; j++)
matrix[i][j] = INF;
while( (ret = fscanf(fp, "%d %d %d", &i, &j, &weight)) != EOF) {
if(ret == 3) {
matrix[i][j] = weight;
#ifdef SYM
matrix[j][i] = weight;
#endif
}
else printf("error reading input\n");
}
fclose(fp);
printMatrix(matrix);
shortestPath(matrix);
printMatrix(matrix);
}
void printMatrix(int m[NMAX][NMAX]) {
int i, j;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
if(m[i][j]==INF) printf(" - "); else printf("%3d ", m[i][j]);
}
printf("\n");
}
}
void shortestPath(int d[NMAX][NMAX]) {
int i, j, k, temp;
// no need to make a copy of the matrix: operate on the original
for(k=0; k<n; k++) {
for(i=0; i<n-1; i++) {
for(j=0; j<n; j++) {
if(i==j) continue; // don't look for a path to yourself...
if(d[i][k] == INF || d[k][j]==INF) continue; // no path if either edge does not exist
if((temp = d[i][k] + d[k][j]) < d[i][j]) {
d[i][j] = temp;
#ifdef SYM
d[j][i] = temp;
#endif
printf("from %d to %d is shorter via %d: %d + %d is %d\n", i, j, k, d[i][k], d[k][j], temp);
}
}
}
}
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
if(d[i][j] < INF) printf("%2d %2d %3d\n", i, j, d[i][j]);
}
}
}
With the following input file:
5
1 2 3
2 4 2
1 4 8
0 3 7
3 1 2
1 4 2
1 3 1
0 1 1
I got as output:
n is 5
- 1 - 7 -
- - 3 1 2
- - - - 2
- 2 - - -
- - - - -
from 0 to 2 is shorter via 1: 1 + 3 is 4
from 0 to 3 is shorter via 1: 1 + 1 is 2
from 0 to 4 is shorter via 1: 1 + 2 is 3
from 3 to 2 is shorter via 1: 2 + 3 is 5
from 3 to 4 is shorter via 1: 2 + 2 is 4
0 1 1
0 2 4
0 3 2
0 4 3
1 2 3
1 3 1
1 4 2
2 4 2
3 1 2
3 2 5
3 4 4
- 1 4 2 3
- - 3 1 2
- - - - 2
- 2 5 - 4
- - - - -
Oddly enough, when I ran your code (as posted above) it gave me the same solution - although the output for the first part made it very clear that the memset wasn't working as you expected:
0 1 252645135 7 252645135
252645135 0 3 1 2
252645135 252645135 0 252645135 2
252645135 2 252645135 0 252645135
252645135 252645135 252645135 252645135 0
0 1 1
0 2 4
0 3 2
0 4 3
1 2 3
1 3 1
1 4 2
2 4 2
3 1 2
3 2 5
3 4 4
In fact, the number that is being written to the matrix with the memset operation is 0x0F0F0F0F, which is 252645135 in decimal. You can understand why this is so by looking at the syntax of memset:
void *memset(void *str, int c, size_t n)
Parameters
str -- This is pointer to the block of memory to fill.
c -- This is the value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
n -- This is the number of bytes to be set to the value.
and combining with the hexadecimal representation of 9999, which is
0x270F
The "unsigned char conversion" of an int is that number modulo 256, or the least significant byte. In this case, the least significant byte is 0x0F and that is the value that gets written (repeatedly) to every byte in the block - hence the value 0x0F0F0F0F (on my machine, an int is four bytes long).
Afterword
Finally - if you want to use "any size of array", you can add the following couple of functions to your program - and replace the function signatures as indicated. This is a "tricky" way to create a two D array of variable size in C - essentially, when C comes across a pointer of the type int** it will dereference twice. By making this pointer-to-a-pointer point to a block of pointers to the block of memory, you create in effect a 2D array that the compiler can understand.
int **make2D(int r, int c) {
int ii, **M;
M = malloc(r * sizeof(int*) );
M[0] = malloc( r * c * sizeof(int) );
for(ii=1; ii<r; ii++) M[ii] = M[0] + ii * c * sizeof(int);
return M;
}
void free2D(int** M) {
free(M[0]);
free(M);
}
Now you generate your matrix with
int **matrix;
matrix = make2D(n, n);
and you change the function signatures to
void shortestPath(int **m);
void printMatrix(int **m);
And call them with
shortestPath(matrix); // etc
To make everything work properly you have to make a few other adjustments in your code (example: you should not try to assign INF to all elements of a NMAX by NMAX array when you allocated less memory than that). You can try to figure this out for yourself - but just in case, here is the complete code. One other change I made - I got rid of n as a global variable and made it local to main (and passed it to the various routines that needed it). This is usually a good practice - it's all too easy to mix things up with globals, so use them only when you really have no choice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INF 9999
#define MIN(a,b)((a)<(b))?(a):(b)
// uncomment the next line to make processing symmetrical
// i.e. undirected edges
// #define SYM
void shortestPath(int **m, int n);
void printMatrix(int **m, int n);
// create 2D matrix of arbitrary (variable) size
// using standard C:
int **make2D(int r, int c) {
int ii, **M;
M = malloc(r * sizeof(int*) );
M[0] = malloc( r * c * sizeof(int) );
for(ii=1; ii<r; ii++) M[ii] = M[0] + ii * c * sizeof(int);
return M;
}
void free2D(int** M) {
free(M[0]);
free(M);
}
// implementation of floyd-warshall algorithm
// with minimal error checking
// input file = series of nodes on graph in form
// start, end, length
// algorithm attempts to find shortest path between any connected nodes
// by repeatedly looking for an intermediate node that shortens the current distance
// graphs are directional - 3 4 5 does not imply 4 3 5
// this can be changed by uncommenting the #define SYM line above
// also, hard coded to have no more than 20 nodes - defined with NMAX above
// path to input file is hard coded as "eg2.txt"
int main(void) {
int i, j, n, weight, ret;
// open input file:
FILE *fp = fopen("eg2.txt", "r");
if(fp == NULL) {
printf("cannot read input file\n");
exit(1);
}
// read number of nodes in the graph:
fscanf(fp, "%d", &n);
printf("n is %d\n", n);
// generate matrix:
int **matrix;
// allocate memory:
matrix = make2D(n, n);
// fill all elements with INF:
for(i=0; i<n;i++)
for(j=0; j<n; j++)
matrix[i][j] = INF;
// read the input file:
while( (ret = fscanf(fp, "%d %d %d", &i, &j, &weight)) != EOF) {
if(ret == 3) {
matrix[i][j] = weight;
#ifdef SYM
// if undirected edges, put in both paths:
matrix[j][i] = weight;
#endif
}
else printf("error reading input\n");
}
fclose(fp);
printMatrix(matrix, n);
shortestPath(matrix, n);
printMatrix(matrix, n);
}
void printMatrix(int **m, int n) {
int i, j;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
if(m[i][j]==INF) printf(" - "); else printf("%3d ", m[i][j]);
}
printf("\n");
}
}
void shortestPath(int **d, int n) {
int i, j, k, temp;
// no need to make a copy of the matrix: operate on the original
for(k=0; k<n; k++) {
for(i=0; i<n-1; i++) {
for(j=0; j<n; j++) {
if(i==j) continue; // don't look for a path to yourself...
if(d[i][k] == INF || d[k][j]==INF) continue; // no path if either edge does not exist
if((temp = d[i][k] + d[k][j]) < d[i][j]) {
d[i][j] = temp;
#ifdef SYM
d[j][i] = temp;
#endif
printf("from %d to %d is shorter via %d: %d + %d is %d\n", i, j, k, d[i][k], d[k][j], temp);
}
}
}
}
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
if(d[i][j] < INF) printf("%2d %2d %3d\n", i, j, d[i][j]);
}
}
}

Resources