1
1
/*
2
- * Problema do Caixeiro Viajante em C
3
- * Utilizando uma matriz de distância para representar um grafo não direcionado .
4
- * Objetivo: Encontrar o menor caminho que passe por todos os vértices sem repetir nenhum, e chegar novamente ao vértice de início
2
+ * Traveling Salesman Problem in C
3
+ * Using a distance matrix to represent an undirected graph .
4
+ * Objective: Find the shortest path that visits all vertices without repeating any, and returns to the starting vertex.
5
5
*
6
6
* 6
7
7
* (4)-----(0)
16
16
* | | 3
17
17
* --------------
18
18
*
19
- *
20
- * Matriz de Distância
19
+ * Distance Matrix
21
20
* 0 1 2 3 4
22
21
* 0 0 2 - 3 6
23
22
* 1 2 0 4 3 -
24
23
* 2 - 4 0 7 3
25
24
* 3 3 3 7 0 3
26
25
* 4 6 - 3 3 0
27
- *
28
- *
29
26
*/
30
27
31
28
#include <stdio.h>
32
29
33
30
#define VERTICES 5
34
- #define INFINITO 429496729
35
-
36
- int tempSolucao [VERTICES ];
37
- int melhorSolucao [VERTICES ];
38
- bool visitados [VERTICES ];
39
- int valorMelhorSolucao = INFINITO ;
40
- int valorSolucaoAtual = 0 ;
31
+ #define INFINITY 429496729
41
32
42
- int matriz [VERTICES ][ VERTICES ] = {{ 0 , 2 , INFINITO , 3 , 6 },
43
- { 2 , 0 , 4 , 3 , INFINITO },
44
- { INFINITO , 4 , 0 , 7 , 3 },
45
- { 3 , 3 , 7 , 0 , 3 },
46
- { 6 , INFINITO , 3 , 3 , 0 }} ;
33
+ int tempSolution [VERTICES ];
34
+ int bestSolution [ VERTICES ];
35
+ bool visited [ VERTICES ];
36
+ int bestSolutionValue = INFINITY ;
37
+ int currentSolutionValue = 0 ;
47
38
48
- void caixeiroViajanteAux (int x ){
49
- // Se o valor da solução atual já estiver maior que o valor da melhor solução já para, pois já não pode mais ser a melhor solução
50
- if ( valorSolucaoAtual > valorMelhorSolucao )
51
- return ;
39
+ int matrix [VERTICES ][VERTICES ] = {{ 0 , 2 , INFINITY , 3 , 6 },
40
+ { 2 , 0 , 4 , 3 , INFINITY },
41
+ { INFINITY , 4 , 0 , 7 , 3 },
42
+ { 3 , 3 , 7 , 0 , 3 },
43
+ { 6 , INFINITY , 3 , 3 , 0 }};
52
44
53
- if ( x == VERTICES ){ // Se x == VERTICES significa que o vetor da solução temporária está completo
54
- int distancia = matriz [tempSolucao [x - 1 ]][tempSolucao [0 ]];
55
- // Se encontrou uma solução melhor/menor
56
- if ( distancia < INFINITO && valorSolucaoAtual + distancia < valorMelhorSolucao ){
57
- valorMelhorSolucao = valorSolucaoAtual + distancia ; // Substitui a melhor solução pela melhor encontrada agora
58
- // Copia todo o vetor de solução temporária para o vetor de melhor solução encontrada
59
- for (int i = 0 ; i < VERTICES ; ++ i ){
60
- melhorSolucao [i ] = tempSolucao [i ];
61
- }
62
- }
63
- return ;
64
- }
45
+ void travelingSalesmanAux (int x ) {
46
+ // If the current solution value is already greater than the best solution, stop as it can't be the best solution
47
+ if (currentSolutionValue > bestSolutionValue )
48
+ return ;
65
49
66
- int ultimo = tempSolucao [x - 1 ]; // Ultimo recebe o número do último vértice que se encontra na solução temporária
67
- // For que percorre todas as colunas da matriz na linha do último vértice do vetor solução temporária
68
- for (int i = 0 ; i < VERTICES ; i ++ ){
69
- // Se a posição i do vetor ainda não foi visitada, e se o valor da matriz na posição é menor que INFINITO
70
- if ( visitados [i ] == false && matriz [ultimo ][i ] < INFINITO ){
71
- visitados [i ] = true; // Marca como visitado
72
- tempSolucao [x ] = i ; // Carrega o vértice que está passando no vetor de solução temporária
73
- valorSolucaoAtual += matriz [ultimo ][i ]; // Incrementa o valor da matriz na variável que guarda o total do caminho percorrido
74
- caixeiroViajanteAux (x + 1 ); // Chama recursivamente para o próximo vértice
75
- valorSolucaoAtual -= matriz [ultimo ][i ]; // Se ainda não terminou, diminuí o valor da váriavel que guarda o total da solução atual
76
- visitados [i ] = false; // Seta como false a posição para poder ser utilizado por outro vértice
77
- }
78
-
79
- }
50
+ if (x == VERTICES ) { // If x == VERTICES, it means the temporary solution array is complete
51
+ int distance = matrix [tempSolution [x - 1 ]][tempSolution [0 ]];
52
+ // If a better (shorter) solution is found
53
+ if (distance < INFINITY && currentSolutionValue + distance < bestSolutionValue ) {
54
+ bestSolutionValue = currentSolutionValue + distance ; // Update the best solution with the new better one
55
+ // Copy the entire temporary solution array to the best solution array
56
+ for (int i = 0 ; i < VERTICES ; ++ i ) {
57
+ bestSolution [i ] = tempSolution [i ];
58
+ }
59
+ }
60
+ return ;
61
+ }
80
62
63
+ int last = tempSolution [x - 1 ]; // 'last' holds the number of the last vertex in the temporary solution array
64
+ // Loop through all columns in the matrix on the row of the last vertex in the temporary solution array
65
+ for (int i = 0 ; i < VERTICES ; i ++ ) {
66
+ // If the i-th vertex hasn't been visited, and the matrix value is less than INFINITY
67
+ if (!visited [i ] && matrix [last ][i ] < INFINITY ) {
68
+ visited [i ] = true; // Mark as visited
69
+ tempSolution [x ] = i ; // Add the current vertex to the temporary solution array
70
+ currentSolutionValue += matrix [last ][i ]; // Increment the path total
71
+ travelingSalesmanAux (x + 1 ); // Recursively call for the next vertex
72
+ currentSolutionValue -= matrix [last ][i ]; // Decrease the path total if not finished yet
73
+ visited [i ] = false; // Mark the vertex as unvisited so it can be used again by another vertex
74
+ }
75
+ }
81
76
}
82
77
83
- void caixeiroViajante (int inicial ) {
84
- visitados [ inicial ] = true; // Marca o primeiro vértice como visitado (0)
85
- tempSolucao [0 ] = inicial ; // Coloca o vértice 0 na primeira posição do vetor de solução temporária
86
- caixeiroViajanteAux (1 ); // Chama o método auxiliar do caixeiro viajante
78
+ void travelingSalesman (int start ) {
79
+ visited [ start ] = true; // Mark the starting vertex as visited (0)
80
+ tempSolution [0 ] = start ; // Place vertex 0 in the first position of the temporary solution array
81
+ travelingSalesmanAux (1 ); // Call the auxiliary function for the traveling salesman problem
87
82
}
88
83
89
- void iniciaVetores () {
90
- for (int i = 0 ; i < VERTICES ; i ++ ){
91
- visitados [i ] = false;
92
- tempSolucao [i ] = -1 ;
93
- melhorSolucao [i ] = -1 ;
94
- }
84
+ void initializeArrays () {
85
+ for (int i = 0 ; i < VERTICES ; i ++ ) {
86
+ visited [i ] = false;
87
+ tempSolution [i ] = -1 ;
88
+ bestSolution [i ] = -1 ;
89
+ }
95
90
}
96
91
97
- int main (){
98
-
99
- iniciaVetores ();
100
- caixeiroViajante (0 );
92
+ int main () {
93
+ initializeArrays ();
94
+ travelingSalesman (0 );
101
95
102
- printf ("Caminho mínimo : %d\n" , valorMelhorSolucao );
103
- for (int i = 0 ; i < VERTICES ; i ++ ){
104
- printf ("%d, " , melhorSolucao [i ]);
105
- }
106
- printf ("\n\n" );
107
- }
96
+ printf ("Minimum path cost : %d\n" , bestSolutionValue );
97
+ for (int i = 0 ; i < VERTICES ; i ++ ) {
98
+ printf ("%d, " , bestSolution [i ]);
99
+ }
100
+ printf ("\n\n" );
101
+ }
0 commit comments