Skip to content

Return an array of anti-diagonals of given N*N square matrix

Problem Description

Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.

Example:

Input:

1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9

Return the following:

[ 
  [1],
  [2, 4],
  [3, 5, 7],
  [6, 8],
  [9]
]
[ 
  [1],
  [2, 4],
  [3, 5, 7],
  [6, 8],
  [9]
]

Input:

1 2
3 4
1 2
3 4

Return the following:

[
  [1],
  [2, 3],
  [4]
]
[
  [1],
  [2, 3],
  [4]
]

Solution

TIP

Two-Dimensionala Array Iteration.

anti-diagonal

swift
import Foundation

class Solution {
	func diagonal(_ A: inout [[Int]]) -> [[Int]] {
        var B = [[Int]](repeating:[Int](),count:A.count*2-1)
        
        for i in 0..<A.count {
            for j in 0..<A.count {
                B[i+j].append(A[i][j])
            }
        }
        return B
	}
}
import Foundation

class Solution {
	func diagonal(_ A: inout [[Int]]) -> [[Int]] {
        var B = [[Int]](repeating:[Int](),count:A.count*2-1)
        
        for i in 0..<A.count {
            for j in 0..<A.count {
                B[i+j].append(A[i][j])
            }
        }
        return B
	}
}

Reference