Java implementation of backtracking method

Java implementation of backtracking method

1. Task

  1. Understand the depth-first search strategy of the backtracking method, and master the algorithm framework for solving problems with the backtracking method
  2. Design and implement the traveling salesman problem, and master the backtracking algorithm.

2. Reference code

import java.util.*;
import java.io.*;

public class TravelingSalesmanProblem {
    
    private static int N; // 城市数量
    private static int[][] distance; // 城市间距离矩阵
    private static boolean[] visited; // 是否访问过某城市
    private static int minDistance = Integer.MAX_VALUE; // 最小距离
    private static List<Integer> minPath; // 记录最短路径
    
    public static void main(String[] args) throws IOException {
        // 读取输入数据
        Scanner scanner = new Scanner(new FileInputStream("input.txt"));
        N = scanner.nextInt();
        distance = new int[N][N];
        visited = new boolean[N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                distance[i][j] = scanner.nextInt();
            }
        }
        scanner.close();
        
        // 回溯求解
        List<Integer> path = new ArrayList<>();
        path.add(0); // 出发城市为0
        visited[0] = true;
        backtrack(path, 0, 0);
        
        // 输出结果到文件output.txt中
        PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
        writer.println(minDistance);
        writer.println(minPath);
        writer.close();
    }
    
    /**
     * 回溯求解
     * @param path 当前路径
     * @param curDistance 当前距离
     * @param curCity 当前城市
     */
    private static void backtrack(List<Integer> path, int curDistance, int curCity) {
        if (path.size() == N) { // 路径已经遍历完所有城市,更新最小距离和路径
            curDistance += distance[curCity][0];
            if (curDistance < minDistance) {
                minDistance = curDistance;
                minPath = new ArrayList<>(path);
                minPath.add(0);
            }
            return;
        }
        if (curDistance >= minDistance) { // 剪枝:当前路径距离已经大于最小距离,不必继续搜索
            return;
        }
        for (int i = 0; i < N; i++) {
            if (!visited[i]) {
                visited[i] = true;
                path.add(i);
                backtrack(path, curDistance + distance[curCity][i], i);
                path.remove(path.size() - 1);
                visited[i] = false;
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_41957626/article/details/131216017
Recommended