【发布时间】:2021-05-13 18:17:41
【问题描述】:
我一直在加深对 LeetCode 上无向图与无向图问题算法的理解。我意识到的关键区别是像841 Keys and Rooms 这样的问题,因为这是定向的,我需要将“0”节点添加到可见集。特别是早期的这一行:
seen_rooms.add(0)
另一方面,对于547. Number of Provinces,由于图形是无向的,我从不需要“提前”添加它。我可以稍后在我的循环中添加它
问题 547:
class Solution():
def findCircleNum(self, A):
#Finds your neighboring cities
seen_cities = set()
def find_cities(cur_city):
nei_cities = A[cur_city]
#First iter (0) nei city
#cur_city = 0
#find_cities (0) go through neighbors of 0
#Don't need to add b/c this is going through it each time so when 1 -> 2 we would have had 1 <- 2 as well
# seen_cities.add(cur_city)
for nei_city, can_go in enumerate(nei_cities):
if can_go == 1 and nei_city not in seen_cities:
seen_cities.add(nei_city)
find_cities(nei_city)
#Go a DFS on all neighboring cities
provinces = 0
for city in range(len(A)):
#We haven't visited the city
if city not in seen_cities:
# seen_cities.add(city)
find_cities(city)
#After the above DFS I would have found all neighboring cities and increase it's province by 1
#Then go onto the next one's
provinces += 1
return provinces
问题 841
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
#canvisitallrooms
#pos means you can visit such rooms
#This one is directed so u needa add it ahead of time
total_rooms = []
#When adding to the stack we needa add to seen as well
stack = [0]
seen_rooms = set()
seen_rooms.add(0)
#We never necessairly mentioned room 0 so we need to add room 0 since it STARTS there as well compared to another prob like 547
#[[1],[2],[3],[]]
while stack:
cur_room = stack.pop()
nei_rooms = rooms[cur_room]
for nei_room in nei_rooms:
if nei_room not in seen_rooms:
seen_rooms.add(nei_room)
stack.append(nei_room)
return len(seen_rooms) == len(rooms)
对于无向图可以这样做的原因,即不必像我上面所说的那样将位置添加到早期看到的位置,因为它是无向的,我们将再次访问这样的路径并且可以将其添加到已看到的集合中以防止我们再次看到它?而在像钥匙和房间这样的有向图中,我们不会每次都“访问”房间 0 可能吗?
【问题讨论】:
-
能否添加对 leetcode 问题的描述?
标签: python python-3.x algorithm recursion depth-first-search