Gorang implementation of topological sorting - DFS algorithm version

Problem Description: there is a series of numbers 1 to 5, which are rearranged and printed according to the following requirements on order. The requi...

Problem Description: there is a series of numbers 1 to 5, which are rearranged and printed according to the following requirements on order. The requirements are as follows: 2 appears before 5, 3 before 2, 4 before 1, and 1 before 3.

This problem is a very typical topological sorting problem. The general solution to topological sorting is to use DFS depth first algorithm. My shallow understanding of DFS algorithm is recursion. Because there are some preconditions in topological sorting problem itself (this paper only introduces the definition of topological algorithm), so we have the following ideas to solve this problem.

First declare the sorting requirements as a map (take the key and value of the map as the requirements of the order, and the key should appear before the value). Then traverse the numbers 1-5, and find out whether the key in the map exists or not. If it exists, put it into the result array according to the relationship between the key and value in the map. Then use the value obtained from the map[key] to find out whether the key in the map exists. If it exists, put the new key and value into one end of the result array, and so on. Finally, print the result array, which should meet the requirements of this topic. Let's implement the above problems with Golang.

package main import ( "fmt" "strconv" ) //Order of edge requirements var edge map[string]string = map[string]string{ "2": "5", "3": "2", "4": "1", "1": "3", } func main() { //Result array var q []string = make([]string, 0) //Array accessed var visited []string = make([]string, 0) for i := 0; i < 5; i++ { tupusort(&q, &visited, strconv.Itoa(i)) } // fmt.Printf("visited: %v \n", visited) reverse(q) fmt.Printf("topusort: %v \n", q) } //Topology sort DFS func tupusort(q *[]string, visited *[]string, element string) { if !isVisited(visited, element) { *visited = append(*visited, element) if edge[element] != "" { tupusort(q, visited, edge[element]) } *q = append(*q, element) } } //Check if there is an array that has been accessed func isVisited(visited *[]string, element string) bool { var isVisited bool = false for _, item := range *visited { if item == element { isVisited = true break } } return isVisited } //Reverse array order func reverse(arr []string) { for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 { arr[i], arr[j] = arr[j], arr[i] } }

The final output is

topusort: [4 1 3 2 5 0]

4 November 2019, 12:29 | Views: 2412

Add new comment

For adding a comment, please log in
or create account

0 comments