Diagonal traverse. Meaning of the questions is to give a two-dimensional array, in accordance with the rules of traversal, the output of a one-dimensional array. example,
Example:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9]![]()
The question is no algorithm, the difficulty is how to determine in the end is up or down scanning scans and how to determine the boundary conditions.
If the traversal is first discovered from lower left to upper right, the vertical and horizontal traversing point coordinates plus and (x + y)% 2 === 0; if it is left on the lower right traversal, the traversal of the vertical and horizontal coordinates of the point plus and (x + y)% 2 === 1. This is limited to a conclusion this question . Boundary conditions encountered only two possibilities, one to go on the lower left to the right time to ensure the right of the vertical axis do not exceed the boundaries of not less than 0 and the horizontal axis; the second is the upper right to left when laid down to ensure that not less than 0 abscissa and ordinate Do out of bounds on the left.
Time O (m * n)
Space O (m * n) - output memory
1 /** 2 * @param {number[][]} matrix 3 * @return {number[]} 4 */ 5 var findDiagonalOrder = function (matrix) { 6 // corner case 7 if (matrix.length === 0) { 8 return []; 9 } 10 11 // normal case 12 let row = 0; 13 let col = 0; 14 let m = matrix.length; 15 let n = matrix[0].length; 16 let res = []; 17 for (let k = 0; k < m * n; k++) { 18 res.push(matrix[row][col]); 19 // moving up 20 if ((row + col) % 2 === 0) { 21 if (col === n - 1) { 22 row++; 23 } else if (row === 0) { 24 col++; 25 } else { 26 row--; 27 col++; 28 } 29 } 30 // moving down 31 else { 32 if (row === m - 1) { 33 col++; 34 } else if (col === 0) { 35 row++; 36 } else { 37 row++; 38 col--; 39 } 40 } 41 } 42 return res; 43 };