Skip to content

Commit 1900374

Browse files
committed
498. Diagonal Traverse
1 parent ed8ae23 commit 1900374

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

diagonal-traverse/Readme.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# 498. Diagonal Traverse
2+
3+
Source: https://leetcode.com/problems/diagonal-traverse/description/
4+

diagonal-traverse/main.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package leecode
2+
3+
func findDiagonalOrder(matrix [][]int) []int {
4+
m := len(matrix)
5+
if m == 0 {
6+
return []int{}
7+
}
8+
n := len(matrix[0])
9+
if m == 1 && n == 1 {
10+
return matrix[0]
11+
}
12+
ret := []int{}
13+
var row, col int
14+
for i := 0; i < m*n; i++ {
15+
ret = append(ret, matrix[row][col])
16+
if (row+col)%2 == 0 { // moving up
17+
if col == n-1 {
18+
row++
19+
continue
20+
}
21+
if row == 0 {
22+
col++
23+
continue
24+
}
25+
row--
26+
col++
27+
} else { // moving down
28+
if row == m-1 {
29+
col++
30+
continue
31+
}
32+
if col == 0 {
33+
row++
34+
continue
35+
}
36+
row++
37+
col--
38+
}
39+
}
40+
return ret
41+
}

diagonal-traverse/main_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package leecode
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"testing"
7+
)
8+
9+
func TestFindDiagonalOrder(t *testing.T) {
10+
testCases := []struct {
11+
Input [][]int
12+
Output []int
13+
}{
14+
{
15+
Input: [][]int{},
16+
Output: []int{},
17+
},
18+
{
19+
Input: [][]int{
20+
{1},
21+
},
22+
Output: []int{1},
23+
},
24+
{
25+
Input: [][]int{
26+
{1, 2, 3},
27+
{4, 5, 6},
28+
{7, 8, 9},
29+
},
30+
Output: []int{1, 2, 4, 7, 5, 3, 6, 8, 9},
31+
},
32+
}
33+
for _, tc := range testCases {
34+
t.Run(fmt.Sprintf("%v:%d", tc.Input, tc.Output), func(t *testing.T) {
35+
actual := findDiagonalOrder(tc.Input)
36+
if !reflect.DeepEqual(actual, tc.Output) {
37+
t.Errorf("expected %d, but get %d", tc.Output, actual)
38+
}
39+
})
40+
}
41+
}

0 commit comments

Comments
 (0)