-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
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
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
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 | ||
} |
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
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) | ||
} | ||
} | ||
} |