Open azl397985856 opened 3 years ago
class Solution:
def solve(self, graph, target):
q = collections.deque([target])
visited = set()
steps = 0
while q:
for i in range(len(q)):
cur = q.popleft()
visited.add(cur)
for neighbor in graph[cur]:
if neighbor not in visited:
q.append(neighbor)
elif neighbor == target:
return steps + 1
steps += 1
return -1
class Solution {
public int solve(int[][] graph, int target) {
boolean[] visited = new boolean[graph.length];
Queue<Integer> q = new LinkedList<>();
q.add(target);
int level = 0;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
int tmp = q.remove();
visited[tmp] = true;
for (int neighbor : graph[tmp]) {
if (neighbor == target)
return level + 1;
else if (!visited[neighbor])
q.add(neighbor);
}
}
level++;
}
return -1;
}
}
class Solution:
def solve(self, graph, target):
q = collections.deque([target])
visited = set()
steps = 0
while q:
for i in range(len(q)):
cur = q.popleft()
visited.add(cur)
for neighbor in graph[cur]:
if neighbor not in visited:
q.append(neighbor)
elif neighbor == target:
return steps + 1
steps += 1
return -
时间复杂度:O(v+e) 空间复杂度:O(v)
Day52-Shortest-Cycle-Containing-Target-Node
https://binarysearch.com/problems/Shortest-Cycle-Containing-Target-Node
参考题解 - BFS,反向搜索
class Solution:
def solve(self, graph, target):
q = collections.deque([target])
visited = set()
steps = 0
while q:
for i in range(len(q)):
cur = q.popleft()
visited.add(cur)
for neighbor in graph[cur]:
if neighbor not in visited:
q.append(neighbor)
elif neighbor == target:
return steps + 1
steps += 1
return -1
BFS,用d记录已遍历的结点,防止进入别的环。跟着环走,碰到原点则返回长度,全部遍历仍没到原点则返回-1。
class Solution:
def solve(self, graph, target):
d=defaultdict(int)
queue=[(target,0)]
d[target]=1
while len(queue)>0:
node,depth=queue.pop(0)
for i in graph[node]:
if i==target:
return depth+1
if i not in d:
d[i]=1
queue.append((i,depth+1))
return -1
时间:O(V+E)
空间:O(V)
You are given a two-dimensional list of integers graph representing a directed graph as an adjacency list. You are also given an integer target.
Return the length of a shortest cycle that contains target. If a solution does not exist, return -1.
Constraints
n, m ≤ 250 where n and m are the number of rows and columns in graph https://binarysearch.com/problems/Shortest-Cycle-Containing-Target-Node