помоги исправить ошибку в Leetcode 1462 задаче: There are a total of numCourses courses…
- User
помоги исправить ошибку в Leetcode 1462 задаче:
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1. Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
мое решение:
"
1) топологическая сортировка
2) обработка топ. сортировки с учетом транзитивности из условия
from collections import deque
class Solution:
adj_list = None indegree = None def _helper(self, prerequisites, n): self.adj_list = defaultdict(list) self.indegree = [0] * n for u, v in prerequisites: self.adj_list[u].append(v) self.indegree[v] += 1 def _topo_sort(self): topo_sort = list() queue = deque() for ind in range(len(self.indegree)): if self.indegree[ind] == 0: queue.append(ind) while queue: extr = queue.popleft() topo_sort.append(extr) for neigh_node in self.adj_list[extr]: self.indegree[neigh_node] -= 1 if self.indegree[neigh_node] == 0: queue.append(neigh_node) return topo_sort @staticmethod def _handler(string, a, b): ''' функция проверяет что в string есть вхождение элементов a, b такое что а раньше b ''' was_a, was_b = False, False for letter in string: if letter == a: was_a = True if was_a and letter == b: return True return False def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: self._helper(prerequisites, numCourses) topo = self._topo_sort() print(topo) s_topo = "".join(list(map(str, topo))) print(s_topo) ans = list() for pair in queries: ans.append(Solution._handler(s_topo, str(pair[0]), str(pair[1]))) return ans"
дает ошибку на: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
my ans is [false, true] but correct ans is [false, false]
- Assistant