File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
Algorithms/Diagonal Traverse Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ // Source : https://leetcode.com/problems/diagonal-traverse/
2+ // Author : Han Zichi
3+ // Date : 2017-02-07
4+
5+ /**
6+ * @param {number[][] } matrix
7+ * @return {number[] }
8+ */
9+ var findDiagonalOrder = function ( matrix ) {
10+ let M = matrix . length ;
11+ if ( ! M ) return [ ] ;
12+ let N = matrix [ 0 ] . length ;
13+
14+ let res = [ ] ;
15+
16+ // first row
17+ for ( let i = 0 ; i < N ; i ++ ) {
18+ let x = 0
19+ , y = i
20+ , tmp = [ ] ;
21+
22+ while ( true ) {
23+ tmp . push ( matrix [ x ] [ y ] ) ;
24+ x ++ ;
25+ y -- ;
26+
27+ if ( x < 0 || x >= M || y < 0 || y >= N )
28+ break ;
29+ }
30+
31+ res . push ( tmp ) ;
32+ }
33+
34+ // last column
35+ for ( let i = 1 ; i < M ; i ++ ) {
36+ let x = i
37+ , y = N - 1
38+ , tmp = [ ] ;
39+
40+ while ( true ) {
41+ tmp . push ( matrix [ x ] [ y ] ) ;
42+ x ++ ;
43+ y -- ;
44+
45+ if ( x < 0 || x >= M || y < 0 || y >= N )
46+ break ;
47+ }
48+
49+ res . push ( tmp ) ;
50+ }
51+
52+ let ans = [ ] ;
53+ res . forEach ( function ( item , index ) {
54+ if ( ! ( index & 1 ) ) {
55+ ans . push ( ...item . reverse ( ) ) ;
56+ } else {
57+ ans . push ( ...item ) ;
58+ }
59+ } ) ;
60+
61+ return ans ;
62+ } ;
You can’t perform that action at this time.
0 commit comments