leetcode5000. 从始点到终点的所有路径

96 篇文章 1 订阅
81 篇文章 1 订阅

看到这题的时候,第一反应就是每个节点的下一个节点的个数不确定,所以没办法用数组来表示,所以选择使用Map<Integer, List>
然后之前用过Stack来表示路径,所以初始代码如下(执行时间59ms):

Map<Integer, List<Integer>> map = new HashMap<>();
public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
    for (int i = 0; i < edges.length; i++) {
        if (map.containsKey(edges[i][0])) {
            map.get(edges[i][0]).add(edges[i][1]);
        } else {
            List<Integer> list = new ArrayList<>();
            list.add(edges[i][1]);
            map.put(edges[i][0], list);
        }
    }
    Stack<Integer> stack = new Stack<>();
    return leadsToDestination(source, stack, destination);

}

private boolean leadsToDestination(int source, Stack<Integer> stack, int destination) {
    List<Integer> list = map.get(source);
    if (list == null) {
        if (source != destination) {
            return false;
        } else {
            return true;
        }
    }
    for (Integer i : list) {
        if (stack.contains(i)) {
            return false;
        }
        stack.add(i);
        boolean la = leadsToDestination(i, stack, destination);
        if (!la) {
            return false;
        } else {
            stack.pop();
        }
    }
    return true;
}

看了第一名的代码。如醍醐灌顶,不能用数组,可以用链表啊,可以用boolean值来表示路径啊
新的代码如下(9ms):

class Node {
    int val;
    Node next;
    public Node() {

    }
    public Node(int n) {
        val = n;
        next = null;
    }
}

boolean[] used;
public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
    Node[] nodes = new Node[n];
    for (int i = 0; i < n; i++) {
        nodes[i] = new Node(i);
    }
    used = new boolean[n];
    //将edges[i][1]放到edges[i][0]的next中,相当于数组,比数组好的是不需要扩容
    for (int i = 0; i < edges.length; i++) {
        Node node = new Node(edges[i][1]);
        node.next = nodes[edges[i][0]].next;
        nodes[edges[i][0]].next = node;
    }
    return leadsToDestination(source, nodes, destination);

}

private boolean leadsToDestination(int sta, Node[] nodes, int destination) {
    if (nodes[sta].next == null) {
        if (sta == destination) {
            return true;
        } else {
            return false;
        }
    }
    used[sta] = true;
    Node p = nodes[sta].next;
    while (p != null) {
        if (used[p.val] == true) {
            return false;
        }
        if (!leadsToDestination(p.val, nodes, destination)) {
            return false;
        }
        p = p.next;
    }
    used[sta] = false;
    return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值