11/*
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.
55*
66* 6
77* (4)-----(0)
1616* | | 3
1717* --------------
1818*
19- *
20- * Matriz de Distância
19+ * Distance Matrix
2120* 0 1 2 3 4
2221* 0 0 2 - 3 6
2322* 1 2 0 4 3 -
2423* 2 - 4 0 7 3
2524* 3 3 3 7 0 3
2625* 4 6 - 3 3 0
27- *
28- *
2926*/
3027
3128#include <stdio.h>
29+ #include <stdbool.h>
3230
3331#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 ;
32+ #define INFINITY 429496729
4133
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 }} ;
34+ int tempSolution [VERTICES ];
35+ int bestSolution [ VERTICES ];
36+ bool visited [ VERTICES ];
37+ int bestSolutionValue = INFINITY ;
38+ int currentSolutionValue = 0 ;
4739
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 ;
40+ int matrix [VERTICES ][VERTICES ] = {{ 0 , 2 , INFINITY , 3 , 6 },
41+ { 2 , 0 , 4 , 3 , INFINITY },
42+ { INFINITY , 4 , 0 , 7 , 3 },
43+ { 3 , 3 , 7 , 0 , 3 },
44+ { 6 , INFINITY , 3 , 3 , 0 }};
5245
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- }
46+ void travelingSalesmanAux (int x ) {
47+ // If the current solution value is already greater than the best solution, stop as it can't be the best solution
48+ if (currentSolutionValue > bestSolutionValue )
49+ return ;
6550
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- }
51+ if (x == VERTICES ) { // If x == VERTICES, it means the temporary solution array is complete
52+ int distance = matrix [tempSolution [x - 1 ]][tempSolution [0 ]];
53+ // If a better (shorter) solution is found
54+ if (distance < INFINITY && currentSolutionValue + distance < bestSolutionValue ) {
55+ bestSolutionValue = currentSolutionValue + distance ; // Update the best solution with the new better one
56+ // Copy the entire temporary solution array to the best solution array
57+ for (int i = 0 ; i < VERTICES ; ++ i ) {
58+ bestSolution [i ] = tempSolution [i ];
59+ }
60+ }
61+ return ;
62+ }
8063
64+ int last = tempSolution [x - 1 ]; // 'last' holds the number of the last vertex in the temporary solution array
65+ // Loop through all columns in the matrix on the row of the last vertex in the temporary solution array
66+ for (int i = 0 ; i < VERTICES ; i ++ ) {
67+ // If the i-th vertex hasn't been visited, and the matrix value is less than INFINITY
68+ if (!visited [i ] && matrix [last ][i ] < INFINITY ) {
69+ visited [i ] = true; // Mark as visited
70+ tempSolution [x ] = i ; // Add the current vertex to the temporary solution array
71+ currentSolutionValue += matrix [last ][i ]; // Increment the path total
72+ travelingSalesmanAux (x + 1 ); // Recursively call for the next vertex
73+ currentSolutionValue -= matrix [last ][i ]; // Decrease the path total if not finished yet
74+ visited [i ] = false; // Mark the vertex as unvisited so it can be used again by another vertex
75+ }
76+ }
8177}
8278
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
79+ void travelingSalesman (int start ) {
80+ visited [ start ] = true; // Mark the starting vertex as visited (0)
81+ tempSolution [0 ] = start ; // Place vertex 0 in the first position of the temporary solution array
82+ travelingSalesmanAux (1 ); // Call the auxiliary function for the traveling salesman problem
8783}
8884
89- void iniciaVetores () {
90- for (int i = 0 ; i < VERTICES ; i ++ ){
91- visitados [i ] = false;
92- tempSolucao [i ] = -1 ;
93- melhorSolucao [i ] = -1 ;
94- }
85+ void initializeArrays () {
86+ for (int i = 0 ; i < VERTICES ; i ++ ) {
87+ visited [i ] = false;
88+ tempSolution [i ] = -1 ;
89+ bestSolution [i ] = -1 ;
90+ }
9591}
9692
97- int main (){
98-
99- iniciaVetores ();
100- caixeiroViajante (0 );
93+ int main () {
94+ initializeArrays ();
95+ travelingSalesman (0 );
10196
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- }
97+ printf ("Minimum path cost : %d\n" , bestSolutionValue );
98+ for (int i = 0 ; i < VERTICES ; i ++ ) {
99+ printf ("%d, " , bestSolution [i ]);
100+ }
101+ printf ("\n\n" );
102+ }
0 commit comments