Skip to content

Commit

Permalink
Merge 9adac51 into c969b2c
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz authored Mar 7, 2020
2 parents c969b2c + 9adac51 commit 4bb3481
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -462,4 +462,5 @@ problems from
* [Day 463](https://github.com/vaskoz/dailycodingproblem-go/issues/937)
* [Day 464](https://github.com/vaskoz/dailycodingproblem-go/issues/935)
* [Day 465](https://github.com/vaskoz/dailycodingproblem-go/issues/933)
* [Day 473](https://github.com/vaskoz/dailycodingproblem-go/issues/939)

23 changes: 23 additions & 0 deletions day473/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package day473

// AdjacencyMatrix is a directed graph adjacency matrix.
type AdjacencyMatrix map[rune]map[rune]struct{}

// ReverseDirectedGraph reverses all the edges in a given
// directed graph.
// Runs in O(N) time and produces a new graph using O(N) space.
func ReverseDirectedGraph(g AdjacencyMatrix) AdjacencyMatrix {
reversed := make(AdjacencyMatrix, len(g))

for a := range g {
for b := range g[a] {
if _, found := reversed[b]; !found {
reversed[b] = make(map[rune]struct{})
}

reversed[b][a] = struct{}{}
}
}

return reversed
}
48 changes: 48 additions & 0 deletions day473/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package day473

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
g, reversed AdjacencyMatrix
}{
{
AdjacencyMatrix{
'A': {
'B': struct{}{},
},
'B': {
'C': struct{}{},
},
},
AdjacencyMatrix{
'C': {
'B': struct{}{},
},
'B': {
'A': struct{}{},
},
},
},
}

func TestReverseDirectedGraph(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if reversed := ReverseDirectedGraph(tc.g); !reflect.DeepEqual(reversed, tc.reversed) {
t.Errorf("Expected %v, got %v", tc.reversed, reversed)
}
}
}

func BenchmarkReverseDirectedGraph(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
ReverseDirectedGraph(tc.g)
}
}
}

0 comments on commit 4bb3481

Please sign in to comment.