LeetCode 847 题解

https://leetcode.com/problems/shortest-path-visiting-all-nodes/description/

题目大意:N个点组成的无向图,选一个起点遍历完所有点的最小步数。

解题思路:这题难点在于,走过的点可以重复走,如果直接暴力搜索不能确定停止的条件。

考虑用Bitset来表示目前已经遍历过的点的状态,和此时的点 即 dp[i][status]来表示到目前记录目前为止的最小距离,可以用BFS的方式搜索出遍历完所有点的最小距离。

class Solution {
    public int shortestPathLength(int[][] graph) {
        int n=graph.length;
        int[][] dp = new int[n][1<<n];
        Queue<Pair> qt = new LinkedList<>();
        for(int i=0;i<n;i++)
        {
            Arrays.fill(dp[i],999);
            qt.offer(new Pair(i,1<<i));
            dp[i][1<<i] = 0;
        }
        int endStatus = (1<<n) -1;
        while(!qt.isEmpty())
        {
            Pair pi = qt.poll();
            int head = pi.head;
            int d = dp[head][pi.status];
            //System.out.println(pi.status+" "+endStatus+" "+d);
            if( pi.status == endStatus) return d;
            for(int i=0;i<graph[head].length;i++)
            {
                int tmp = graph[head][i];
                int tmpStatus = pi.status | (1<<tmp) ;
                if( d+1 < dp[tmp][tmpStatus])
                {
                    dp[tmp][tmpStatus] = d+1 ;
                    qt.offer(new Pair(tmp,tmpStatus));
                }
            }
        }
        return 0;
    }
}

class Pair{
    public int head,status;

    public Pair(int head, int status) {
        this.head = head;
        this.status = status;
    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值