Skip to content

Commit 32e863d

Browse files
committed
Merge branch 'main' of /Users/izharishaksa/GitHub/leetcode-solutions-golang with conflicts.
1 parent d08816f commit 32e863d

File tree

2 files changed

+109
-0
lines changed

2 files changed

+109
-0
lines changed

build-a-matrix-with-conditions.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package leetcode_solutions_golang
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int {
8+
orderByRow, err := buildTopologicalSort(k, rowConditions)
9+
if err != nil {
10+
return [][]int{}
11+
}
12+
orderByCol, err := buildTopologicalSort(k, colConditions)
13+
if err != nil {
14+
return [][]int{}
15+
}
16+
17+
matrix := make([][]int, k)
18+
for i := 0; i < k; i++ {
19+
matrix[i] = make([]int, k)
20+
for j := 0; j < k; j++ {
21+
if orderByRow[i] == orderByCol[j] {
22+
matrix[i][j] = orderByRow[i]
23+
}
24+
}
25+
}
26+
27+
return matrix
28+
}
29+
30+
func buildTopologicalSort(nNode int, edge [][]int) ([]int, error) {
31+
graph := make(map[int][]int)
32+
inDegree := make(map[int]int)
33+
for i := 0; i < len(edge); i++ {
34+
graph[edge[i][0]] = append(graph[edge[i][0]], edge[i][1])
35+
inDegree[edge[i][1]]++
36+
}
37+
38+
order := make([]int, 0)
39+
for {
40+
next := -1
41+
isCompleted := true
42+
for i := 1; i <= nNode; i++ {
43+
if inDegree[i] >= 0 {
44+
isCompleted = false
45+
}
46+
if inDegree[i] == 0 {
47+
next = i
48+
break
49+
}
50+
}
51+
if isCompleted {
52+
return order, nil
53+
}
54+
if next == -1 {
55+
return nil, fmt.Errorf("cycle detected")
56+
}
57+
58+
order = append(order, next)
59+
inDegree[next] = -1
60+
for _, v := range graph[next] {
61+
inDegree[v]--
62+
}
63+
}
64+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package leetcode_solutions_golang
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
func Test_buildMatrix(t *testing.T) {
9+
type args struct {
10+
k int
11+
rowConditions [][]int
12+
colConditions [][]int
13+
}
14+
tests := []struct {
15+
name string
16+
args args
17+
want [][]int
18+
}{
19+
{
20+
name: "test1",
21+
args: args{
22+
k: 3,
23+
rowConditions: [][]int{{1, 2}, {3, 2}},
24+
colConditions: [][]int{{2, 1}, {3, 2}},
25+
},
26+
want: [][]int{{0, 0, 1}, {3, 0, 0}, {0, 2, 0}},
27+
},
28+
{
29+
name: "test2",
30+
args: args{
31+
k: 3,
32+
rowConditions: [][]int{{1, 2}, {2, 3}, {2, 3}, {2, 1}},
33+
colConditions: [][]int{{2, 1}},
34+
},
35+
want: [][]int{},
36+
},
37+
}
38+
for _, tt := range tests {
39+
t.Run(tt.name, func(t *testing.T) {
40+
if got := buildMatrix(tt.args.k, tt.args.rowConditions, tt.args.colConditions); !reflect.DeepEqual(got, tt.want) {
41+
t.Errorf("buildMatrix() = %v, want %v", got, tt.want)
42+
}
43+
})
44+
}
45+
}

0 commit comments

Comments
 (0)