Created
November 27, 2018 16:46
-
-
Save betandr/35c9b5bbf7a6cd71e8a466fd84f3d460 to your computer and use it in GitHub Desktop.
Graph using maps in Go
This file contains 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
package main | |
import "fmt" | |
var graph = make(map[string]map[string]bool) | |
func addEdge(from, to string) { | |
edges := graph[from] | |
if edges == nil { | |
edges = make(map[string]bool) | |
graph[from] = edges | |
} | |
edges[to] = true | |
} | |
func hasEdge(from, to string) bool { | |
return graph[from][to] | |
} | |
func main() { | |
addEdge("a", "b") | |
addEdge("c", "d") | |
addEdge("a", "d") | |
addEdge("d", "a") | |
fmt.Println(hasEdge("a", "b")) | |
fmt.Println(hasEdge("c", "d")) | |
fmt.Println(hasEdge("a", "d")) | |
fmt.Println(hasEdge("d", "a")) | |
fmt.Println(hasEdge("x", "b")) | |
fmt.Println(hasEdge("c", "d")) | |
fmt.Println(hasEdge("x", "d")) | |
fmt.Println(hasEdge("d", "x")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment