【Lintcode】1422. Shortest Path Visiting All Nodes

题目地址:

https://www.lintcode.com/problem/shortest-path-visiting-all-nodes/description

给定一个 n n n阶无向无权连通图,要求返回一个最短路径的长度,使得该路径访问了所有节点。同一个节点可以被访问多次,同一条边也可以访问多次。边权视为 1 1 1

动态规划解法参考https://blog.csdn.net/qq_46105170/article/details/112761116。下面介绍BFS解法。

把当前到达的位置和已经访问过哪些顶点包装成一个类,这样就把问题转化为,在一个隐式图上求最短路,求的是从任意一个只访问过一个顶点的状态(只访问过一个顶点的状态就是起始状态)到任意一个访问了所有顶点的状态(这就是终止状态)的最短路,而且边权都是 1 1 1,所以可以用BFS来做。存储已经访问过哪些顶点,我们可以用状态压缩来做,用一个整数的二进制位来表示, 1 1 1表示访问过,否则表示未访问过。代码如下:

import java.util.*;

public class Solution {
    
    class Pair {
        int x, state;
        
        public Pair(int x, int state) {
            this.x = x;
            this.state = state;
        }
        
        @Override
        public boolean equals(Object o) {
            Pair pair = (Pair) o;
            return x == pair.x && state == pair.state;
        }
        
        @Override
        public int hashCode() {
            return Objects.hash(x, state);
        }
    }
    
    /**
     * @param graph: the graph
     * @return: the shortest path for all nodes
     */
    public int shortestPathLength(int[][] graph) {
        // Write your code here.
        Queue<Pair> queue = new LinkedList<>();
        Set<Pair> visited = new HashSet<>();
        
        int n = graph.length;
        // 把所有起始点入队并标记为访问过
        for (int i = 0; i < n; i++) {
            Pair start = new Pair(i, 1 << i);
            queue.offer(start);
            visited.add(start);
        }
        
        int res = 0;
        while (!queue.isEmpty()) {
            res++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Pair cur = queue.poll();
                // 枚举能走到哪些顶点
                for (int next : graph[cur.x]) {
                    Pair pair = new Pair(next, cur.state | (1 << next));
                    // 如果走到下一个顶点,就能使得所有顶点都被访问了,那返回最小步数
                    if (pair.state == (1 << n) - 1) {
                        return res;
                    }
                    
                    if (visited.contains(pair)) {
                        continue;
                    }
                    
                    queue.offer(pair);
                    visited.add(pair);
                }
            }
        }
        
        return -1;
    }
}

时空复杂度 O ( n 2 n ) O(n2^n) O(n2n) n 2 n n2^n n2n是所有的状态数的量级。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值