Created
September 15, 2020 11:02
-
-
Save Transfusion/cbbd274fa636acb1303a57e4ecf66ee2 to your computer and use it in GitHub Desktop.
edgelord N tasks topological sorting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # "There's a set of N tasks, from which some have to be done before the other. The order is described by a 2D array T[N][N]. If T[a][b] = 1, then the task 'a' has to be done before the task 'b'. In the case of T[a][b] = 2, the task b has to be done earlier, and when T[a][b] = 0 the order doesn't matter. Implement a function tasks(T), which for the given array T returns an array with the tasks in the order of execution." | |
| # Example: For the array T = [ [0,2,1,1], [1,0,1,1], [2,2,0,1], [2,2,2,0] ] the result is [1,0,2,3] | |
| # an arbitrary array (because there can be more than one solution to a particular graph) | |
| T = [ [0,2,1,1], [1,0,1,1], [2,2,0,1], [2,2,2,0] ] | |
| import sys | |
| v = len(T) # square matrix | |
| m = {} # adj list in a recursively traversable way | |
| for i in range(v): | |
| m[i] = set() | |
| empty_graph = True | |
| for i in range(v): | |
| for j in range(v): | |
| empty_graph = False | |
| if T[i][j] == 1: # a has to be done before b | |
| m[i].add(j) | |
| elif T[i][j] == 2: | |
| m[j].add(i) | |
| if empty_graph: # special case: no edges at all whatsoever! | |
| for i in range(v): | |
| print(i) | |
| sys.exit() | |
| ans = [] | |
| visited = set() | |
| def dfs(v): | |
| visited.add(v) | |
| for next_vertex in m[v]: | |
| if next_vertex not in visited: | |
| dfs(next_vertex) | |
| ans.append(v) | |
| def topological_sort(): | |
| for vertex in m.keys(): | |
| if vertex not in visited: | |
| dfs(vertex) | |
| topological_sort() | |
| print(ans[::-1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment