Sponsored
Sponsored
This approach involves a direct simulation of the diagonal traversal. We use two variables, i
and j
, to represent the current position in the matrix, and a boolean direction
to indicate whether we are moving upwards or downwards diagonally. The process toggles the direction once the boundaries of the matrix are reached, ensuring that the entire matrix is traversed correctly in a zig-zag order.
Time Complexity: O(m * n) as each element is processed once.
Space Complexity: O(m * n) needed for the output array.
1#include <stdio.h>
2#include <stdlib.h>
3
4int* findDiagonalOrder(int** mat, int matSize, int* matColSize, int* returnSize) {
5 if (matSize == 0) {
6 *returnSize = 0;
7 return NULL;
8 }
9 int m = matSize, n = matColSize[0];
10 *returnSize = m * n;
11 int* result = (int*)malloc((*returnSize) * sizeof(int));
12 int idx = 0;
13 int i = 0, j = 0, direction = 1;
14 while (idx < *returnSize) {
15 result[idx++] = mat[i][j];
16 if (direction == 1) { // Moving up
17 if (j == n - 1) { i++; direction = -1; }
18 else if (i == 0) { j++; direction = -1; }
19 else { i--; j++; }
20 } else { // Moving down
21 if (i == m - 1) { j++; direction = 1; }
22 else if (j == 0) { i++; direction = 1; }
23 else { i++; j--; }
24 }
25 }
26 return result;
27}
This C solution simulates diagonal traversal by using a loop that runs until all elements in mat
are processed. By switching the direction
based on boundary conditions, the code alternates between moving upwards and downwards along diagonals. The final result is stored in an array which is returned.
This approach leverages a hash map (or dictionary) to collect elements that belong to the same diagonal. The sum of the row and column indices i + j
serves as the key, grouping all elements located on the same diagonal. After populating the hash map, we extract and append these elements to the result array, reversing them as needed to maintain the diagonal order.
Time Complexity: O(m * n), visits each element once.
Space Complexity: O(m * n), required for temporary storage for diagonals.
1
Using HashMap
, the Java implementation tracks elements by diagonal sums. After accumulating elements in diagonals
, elements are appended to the result list in zig-zag order.