Read multiple matrix from a file using dinamic allocation in c - c

I have an input file like this:
3
7 12 1
1 3 3
2 3 0
12 0 11
7 4 1
1 0 0
The first character tells me the size of the square matrix. Then I have a word that indicates the action to be done and then the matrix. I can't find a way to read the first matrix, use it, deallocate it and then move on to the second and so on. Any help? (I'm using c)
I think I found a solution to allocate the matrix using this code:
int** Matrix;
int n, i;
fscanf(Data, "%d", &n);
Matrice = (int**)calloc(n, sizeof(int*));
for(i=0; i<4; i++)
Matrix[i] = (int*)calloc(n, sizeof(int*));
But this works for the first matrix and I don't know how to treat next matrices to not waste too much memory...

Use a while loop that stops when you reach the end of the file, and create a new matrix with each iteration. This way, you can free each matrix before creating a new one.
(To simplify, this example code works without "ReadMatrix" rows in the input file)
int stop = 0;
while(stop != 1){
Matrix = (int**)calloc(n, sizeof(int*));
for(i=0; i<n; i++) {
Matrix[i] = (int*)calloc(n, sizeof(int));
for(int j=0; j<n; j++) {
if(fscanf (Data, "%d", &Matrix[i][i]) == EOF)
stop = 1;
}
}
//Use the matrix here
//...
for(int i=0; i<n; i++)
free(Matrix[i]);
free(Matrix);
}
Example input:
3
7 12 1
1 3 3
2 3 0
12 0 11
7 4 1
1 0 0

Related

how can I print the final matrix correctly?

Problem Statement
A matrix is a 2D array of numbers arranged in rows and columns. We give you a Matrix of N rows and M columns.
Now your task is to do this operation on this matrix:
If the value matches with the current row and column number then add 3 with the value.
If the value matches with only the current row number then add 2 with the value.
If the value matches with only the current column number then add 1 with the value.
Input Format
The first line contains N is the number of rows in this matrix and M is the number of columns in this matrix
The second line contains a 2D array Arr[i][j].
Constraints
1 <= N, M <= 10
0 <= Arr[i][j] <= 100
Output Format
Print the matrix after the operation is done.
Sample Input 0
3 3
1 1 1
1 1 1
1 1 1
Sample Output 0
4 3 3
2 1 1
2 1 1
#include <stdio.h> 
int main(){
//here taking the row and column from the users
int row;
int column, temp;
printf("enter row and column\n");
scanf("%d%d", &row, &column);
int arr[row][column];
//here taking the matrix input through the users
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
scanf("%d", &arr[i][j]);
}
for (int i=0; i<row; i++){
for(int j=0; j<column; j++ ){
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){
temp= arr[i][j]+3;
printf("%d", temp);
}
else if (arr[i][j] == arr[i+1]){
temp= arr[i][j]+ 2;
printf("%d", temp);
}
else if (arr[i][j]== arr[j+1]){
temp= arr[i][j]+ 1;
printf("%d", temp);
}
else{
temp= arr[i][j];
printf("%d", temp);
}
}
}
}
return 0;
}
After I run the code, this doesn't work.
At least this issue:
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){ is undefined behavior (UB) as code attempts to access outside int arr[row][column]; with arr[i+1] and arr[j+1].
arr[i][j] == arr[i+1] is not sensible as it attempts to compare an int with a pointer.
In c, there are two types of memories. One of them is run-time memory, where your program dynamically allocates memory based on actions done in the program execution time.
In your answer, you are setting your matrix size based on the numbers inputed by the user, which is dynamic memory.
A static array(what you are using) is not dynamic and it is the reason that you can't add more elements and change the size of it.
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/amp/

Rearranging rows in dynamically allocated 2D array in C

I'm currently working on a program in C where I input matrix dimensions and elements of a matrix, which is represented in memory as dynamic 2D array. Program later finds maximum of each row. Then it finds minimal maximum out of maximums of all rows.
For example,
if we have 3x3 matrix:
1 2 3
7 8 9
4 5 6
maximums are 3, 9, 6 and minimal maximum is 3. If minimal maximum is positive, program should proceed with rearranging order of rows so they follow ascending order of maximums, so the final output should be:
1 2 3
4 5 6
7 8 9
I made a dynamic array which contains values of maximums followed by row in which they were found, for example: 3 0 6 1 9 2. But I have no idea what should I do next. It crossed my mind if I somehow figure out a way to use this array with indices I made that I would be in problem if I have same maximum values in different rows, for example if matrix was:
1 2 3
4 5 6
7 8 9
1 1 6
my array would be 3 0 6 1 9 2 6 3. I would then need additional array for positions and it becomes like an inception. Maybe I could use some flag to see if I've already encountered the same number, but I generally, like algorithmically, don't know what to do. It crossed my mind to make an array and transfer values to it, but it would waste additional space... If I found a way to find order in which I would like to print rows, would I need an adress function different than one I already have? (which is, in double for loop, for current element - *(matrix+i * numOfCols+currentCol) ) I would appreciate if somebody told me am I thinking correctly about problem solution and give me some advice about this problem. Thanks in advance!
I don't know if I have understood it correctly, but what you want to do is to rearrange the matrix, arranging the rows by the greatest maximum to the least...
First, I don't think you need the dynamic array, because the maximums are already ordered, and their position on the array is enough to describe the row in which they are.
To order from maximum to minimum, I would make a loop which saved the position of the maximum and then, use it to store the correspondent row in the input matrix into the output matrix. Then, change the value of that maximum to 0 (if you include 0 in positives, then change to -1), and repeat the process until all rows have been passed to the output matrix. Here is a sketch of what it would look like:
for(k = 0; k < n_rows; ++k)
for(i = 0; i < n_rows; ++i)
if (max[i] > current_max)
current_max = max[i];
max_row = i;
for(c = 0; c < n_columns; ++c)
output_matrix[row][c] = inputmatrix[max_row][c];
max[max_row] = 0;
Array is not dynamic because we can not change the size of array, so in this case you can use double pointer, for example, int **matrix to store the value of 2D array.
The function for searching the max value of each row and the row index of each max value:
int * max_of_row(int n, int m, int **mat) {
// allocate for n row and the row index of max value
int *matrix = malloc (sizeof(int) * n*2);
for(int i = 0; i < 2*n; i++) {
matrix[i] = 0;
}
int k = 0;
for(int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(matrix[k] < mat[i][j]) {
matrix[k] = mat[i][j];
}
}
matrix[k+1] = i;
k += 2;
}
return matrix;
}
The main function for test:
int main(int argc, char const *argv[])
{
// allocate for 4 rows
int **matrix = malloc (sizeof (int) * 4);
for (int i = 0; i < 4; i++) {
// allocate for 3 cols
matrix[i] = malloc(sizeof(int) * 3);
for(int j = 0; j < 3; j++){
matrix[i][j] = i+j;
}
}
int * mat = max_of_row(4, 3,matrix);
printf("matrix:\n");
for (int i = 0; i < 4; i++) {
for(int j = 0; j < 3; j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
printf("max of row and positon\n");
for (int i = 0; i < 8; i++) {
printf("%d ", mat[i]);
}
printf("\nmax of row\n");
for (int i = 0; i < 8; i += 2) {
printf("%d ", mat[i]);
}
printf("\n");
return 0;
}
Output:
matrix:
0 1 2
1 2 3
2 3 4
3 4 5
max of row and positon
2 0 3 1 4 2 5 3
max of row
2 3 4 5

How to append values to array in C language

given a set of 10 digit number i need to find how many times the index appears in the give number e.g
given 2 2 0 0 0 3 0 0 1 0 as an array element the array index from 0-9 so i have something like
0 1 2 3 4 5 6 7 8 9
2 2 0 0 0 3 0 0 1 0 ---> input
00115558 -----> output
the first index 0 appear twice, the second index 1 appear twice, the third index 0 appear 0 times so it's ignore and so on so the outcome is 00115558 and now i need to rearrange the output such that 0 must not start so i need something like 10015558
i was able to get the initial output like 00115558, but i need to save it into an array so i can loop through the array and check for value greater than 0 and swap the position.
int main() {
int i,j,len;
int array[10],output[10];
printf("Enter 10 digit number separated by space: \n");
for (i = 0; i < 10; i++)
scanf("%d", &array[i]);
len = sizeof(array)/sizeof(array[0]);
for(i=0; i<len; i++)
{
if(array[i] != 0)
{
for(j=0; j<array[i]; j++)
//output[j] = i;
printf("%d ", i);
}
}
I tried to save the output into another array and i printed the array outside the loop to see the content but the result wasn't what i wanted. How can i save my value into the output[] array. thanks for any help
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,len;
int array[10],output[10];
printf("Enter 10 digit number separated by space: \n");
for (i = 0; i < 10; i++)
scanf("%d", &array[i]);
len = sizeof(array)/sizeof(array[0]);
for(i=0; i<len; i++)
{
if(array[i] != 0)
{
for(j=0; j<array[i]; j++)
//output[j] = i;
printf("%d ", i);
}
}
}
Sir, i tried you exact code as above in "Dev c++". I get answer is 00115558. I think your Code is absolute Right. change your IDE software or Update that.

How do i select a number in a matrix in c?

So I have made a matrix, that's formed by (NxN). And the numbers for the matrix are put in through user input into a multidimensional array. I'm using pointers and malloc. So I have to select a number in the array to then get the sum of adjacent numbers, the number is selected just by saying the position. So just saying the 3rd number in the matrix. I am a little confused on how to just select a number, I have a general idea of incrementing to get to the right position? Would this be right? And will this then make it harder or easier to then get the sum of the adjacent numbers?
Just a little confused on how to then do this with a multidimensional array, would i just turn it back into a single array?
This is how i create the matrix:
for(i = 0; i< matrixSize; i++)
{
for(j=0; j < matrixSize; j++)
{
scanf("%d", &matrixValues[i][j]);
}
}
If you mean number in a matrix as follows (example for matrixSize == 4):
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
you can just calculate indexes from number
matrixValues[number/matrixSize][number%matrixSize]
EDIT:
For case when your 2D arreay defined as
int matrixValues[matrixSize][matrixSize];
All elements allocated in memory sequentially, i.e. element matrixValues[1][0] is exact after matrixValues[0][matrixSize-1], so you can use number as shift from adress of element matrixValues[0][0], e.g.:
*(((int*)matrixValues) + number)
For your example it can be
int matrixValues[matrixSize][matrixSize];
// input as 2D array
int i, j;
for(i = 0; i< matrixSize; i++)
{
for(j=0; j < matrixSize; j++)
{
scanf("%d", &matrixValues[i][j]);
}
}
// using address of matrix as begining of array
int* fakeArray = (int*)matrixValues;
// output as 1D arrray
int n;
for(n = 0; n < matrixSize * matrixSize ; n++)
{
printf("%d ", fakeArray[n]);
}

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