|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Senior Member
Iscritto dal: Aug 2005
Città: Wien
Messaggi: 435
|
[C] Costo minimo
CIao a tutti,
come esercizio all'uni mi hanno dato da scrivere un programma che cerchi il percorso minimo all'interno di una matrice. Il codice l'ho fatto, ora il problema è che vorrei inserire nel array cheapestR gli spostamenti effettuati dall'algoritmo inserendoci all'interno i valori della matrice. Lo so che questa probabilmente è la parte più semplice, ma sono in panne. Codice:
#include <stdio.h>
#include <stdlib.h>
#define n 5
int matrix[n][n] = {{7,3,5,6,1},
{1,6,8,0,2},
{3,5,7,9,2},
{7,6,1,1,4},
{5,7,4,8,2},
};
int cheapestR[n];
int min(int a, int b) {
if (a <= b) {
return a;
} else {
return b;
}
}
int cheapestRec(int r, int c) {
if (r == (n-1)) {
printf("\nRIGA: %d COLONNA: %d ELEMENTO: %d\n", r,c, matrix[r][c]);
return matrix[r][c];
} else if (c == 0) {
printf("\nRIGA: %d COLONNA: %d ELEMENTO: %d\n", r,c, matrix[r][c]);
return matrix[r][c] + min(cheapestRec(r+1,c), cheapestRec(r+1,c+1));
}else if (c == (n-1)) {
printf("\nRIGA: %d COLONNA: %d ELEMENTO: %d\n", r,c, matrix[r][c]);
return matrix[r][c] + min(cheapestRec(r+1,c), cheapestRec(r+1,c-1));
} else {
printf("\nRIGA: %d COLONNA: %d ELEMENTO: %d\n", r,c, matrix[r][c]);
return matrix[r][c] + min(cheapestRec(r+1,c-1), min(cheapestRec(r+1,c), cheapestRec(r+1,c+1)));
}
}
int start() {
return min(cheapestRec(0,0),min(cheapestRec(0,1), min(cheapestRec(0,2),min(cheapestRec(0,3), cheapestRec(0,4)))));
}
int main() {
print();
printf("\n\nRESULT = %d\n",start());
printPath();
return 0;
}
__________________
"Sono 126 miglia per Chicago. Abbiamo il serbatoio pieno, mezzo pacchetto di sigarette, è buio, e portiamo tutt'e due gli occhiali da sole" |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 19:39.



















