Advertisement
1988coder

498. Diagonal Traverse

Mar 10th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/diagonal-traverse/
  2.  
  3. /**
  4.  * r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all
  5.  * on same diagonal with r+c =2. If you check the directions of diagonals, first
  6.  * diagonal is up, second diagonal is down third one is up and so on.. therefore
  7.  * (r+c)%2 simply determines direction.
  8.  *
  9.  * Time Complexity: O(M*N)
  10.  *
  11.  * Space Complexity: O(1) without considering result space.
  12.  *
  13.  * M = Number of rows. N = Number of columns.
  14.  */
  15. class Solution {
  16.     public int[] findDiagonalOrder(int[][] matrix) {
  17.         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  18.             return new int[0];
  19.         }
  20.  
  21.         int r = 0;
  22.         int c = 0;
  23.         int rows = matrix.length;
  24.         int cols = matrix[0].length;
  25.  
  26.         int[] result = new int[rows * cols];
  27.  
  28.         for (int i = 0; i < result.length; i++) {
  29.             result[i] = matrix[r][c];
  30.  
  31.             if ((r + c) % 2 == 0) { // Move Up
  32.                 if (c == cols - 1) {
  33.                     // Reached last column. Now move to below cell in the same column.
  34.                     r++;
  35.                 } else if (r == 0) {
  36.                     // Reached first row. Now move to next cell in the same row.
  37.                     c++;
  38.                 } else {
  39.                     // Somewhere in middle. Keep going up diagonally.
  40.                     r--;
  41.                     c++;
  42.                 }
  43.             } else { // Move Down
  44.                 if (r == rows - 1) {
  45.                     // Reached last row. Now move to next cell in same row.
  46.                     c++;
  47.                 } else if (c == 0) {
  48.                     // Reached first columns. Now move to below cell in the same column.
  49.                     r++;
  50.                 } else {
  51.                     // Somewhere in middle. Keep going down diagonally.
  52.                     r++;
  53.                     c--;
  54.                 }
  55.             }
  56.         }
  57.  
  58.         return result;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement