看到这题的时候,第一反应就是每个节点的下一个节点的个数不确定,所以没办法用数组来表示,所以选择使用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;
}