| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.SortMatrixByDiagonals; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class SortMatrixByDiagonalsSimulation : ISortMatrixByDiagonals |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n^2 log n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="grid"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int[][] SortMatrix(int[][] grid) |
| | 4 | 24 | | { |
| | 4 | 25 | | var n = grid.Length; |
| | | 26 | | |
| | 4 | 27 | | if (n == 1) |
| | 1 | 28 | | { |
| | 1 | 29 | | return grid; |
| | | 30 | | } |
| | | 31 | | |
| | 3 | 32 | | Span<int> items = stackalloc int[n * n]; |
| | | 33 | | |
| | 16 | 34 | | for (var i = 0; i < n - 1; i++) |
| | 5 | 35 | | { |
| | 5 | 36 | | var index = 0; |
| | | 37 | | |
| | 34 | 38 | | for (var j = 0; i + j < n; j++) |
| | 12 | 39 | | { |
| | 12 | 40 | | items[index] = grid[i + j][j]; |
| | | 41 | | |
| | 12 | 42 | | index++; |
| | 12 | 43 | | } |
| | | 44 | | |
| | 14 | 45 | | items[..index].Sort((a, b) => b.CompareTo(a)); |
| | | 46 | | |
| | 34 | 47 | | for (var j = 0; j < index; j++) |
| | 12 | 48 | | { |
| | 12 | 49 | | grid[i + j][j] = items[j]; |
| | 12 | 50 | | } |
| | 5 | 51 | | } |
| | | 52 | | |
| | 10 | 53 | | for (var j = 1; j < n - 1; j++) |
| | 2 | 54 | | { |
| | 2 | 55 | | var index = 0; |
| | | 56 | | |
| | 12 | 57 | | for (var i = 0; j + i < n; i++) |
| | 4 | 58 | | { |
| | 4 | 59 | | items[index] = grid[i][j + i]; |
| | | 60 | | |
| | 4 | 61 | | index++; |
| | 4 | 62 | | } |
| | | 63 | | |
| | 2 | 64 | | items[..index].Sort(); |
| | | 65 | | |
| | 12 | 66 | | for (var i = 0; i < index; i++) |
| | 4 | 67 | | { |
| | 4 | 68 | | grid[i][j + i] = items[i]; |
| | 4 | 69 | | } |
| | 2 | 70 | | } |
| | | 71 | | |
| | 3 | 72 | | return grid; |
| | 4 | 73 | | } |
| | | 74 | | } |