[Python 3] Explanation with pictures, Topological Sort
Detect if a circle exists in DAG\n\nHere is the BFS solution: start with dequeue of nodes with 0 indegree, update the indegree and add those nodes with 0 indegr
> Detect if a circle exists in DAG\n\nHere is the BFS solution: start with dequeue of nodes with 0 indegree, update the indegree and add those nodes with 0 indegree to dequeue. Once we are done, the sequence by which we pop the nodes are **one** workable order. \n\n![image](https://assets.leetcode.com/users/images/ff809462-2a9c-4919-857c-a21e67bc3843_1661659335.123167.png)\n\n![image](https://assets.leetcode.com/users/images/8abc7101-06c5-437c-8fb7-50fd7c5a0ffc_1661659339.089174.png)\n\n![image](https://assets.leetcode.com/users/images/51869dd3-39c5-4576-9a34-70f5f8c8edcf_1661659342.2771084.png)\n\n> If there exists a circle, the nodes on circle will never be visited. Thus we end up with a sequence shorter than the total number of nodes.\n\n![image](https://assets.leetcode.com/users/images/aad489c2-73ee-4f8c-8b50-273f6b75c057_1661659345.178224.png)\n\nOnce we find a proper order for both the rows and cols, just add the number back to an empty matrix accordingly.\n\n\n**python**\n\n```\ndef buildMatrix(self, k: int, R: List[List[int]], C: List[List[int]]) -> List[List[int]]:\n        def helper(A):\n            nxt, indegree = [set() for _ in range(k)], [0] * k\n            dq, ans = collections.deque(), []\n            A = set([tuple(a) for a in A])  \n            for i, j in A:\n                nxt[i - 1].add(j - 1)\n                indegree[j - 1] += 1\n            for i in range(k):\n                if indegree[i] == 0:\n                    dq.append(i)   \n            while dq:\n                cur = dq.popleft()\n                ans.append(cur)\n                for cand in nxt[cur]:\n                    indegree[cand] -= 1\n                    if indegree[cand] == 0:\n                        dq.append(cand)       \n            return ans if len(ans) == k else []\n        \n        ans1, ans2 = helper(R), helper(C)\n        if not ans1 or not ans2: \n            return []\n\n        A = [[0] * k for _ in range(k)]\n        for i in range(k): \n            A[ans1.index(i)][ans2.index(i)] = i + 1\n        return A\n```
[]