2508/FindDiagonalOrder #2

Merged
mhhung merged 4 commits from 2508/FindDiagonalOrder into main 2025-08-25 03:58:50 +00:00
2 changed files with 82 additions and 2 deletions
Showing only changes of commit b8a053eff1 - Show all commits

View File

@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FindDiagonalOrder", "FindDiagonalOrder.csproj", "{B3151728-C057-4305-DD4C-9A2AFBFC189A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B3151728-C057-4305-DD4C-9A2AFBFC189A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3151728-C057-4305-DD4C-9A2AFBFC189A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3151728-C057-4305-DD4C-9A2AFBFC189A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3151728-C057-4305-DD4C-9A2AFBFC189A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DB56539A-6F32-4D28-B91F-BB1DCF46F4D0}
EndGlobalSection
EndGlobal

View File

@@ -1,5 +1,61 @@
public class Solution {
public int[] FindDiagonalOrder(int[][] mat) {
public int[] FindDiagonalOrder(int[][] mat)
{
if (mat == null || mat.Length == 0 || mat[0].Length == 0)
{
return new int[0];
}
var m = mat.Length;
var n = mat[0].Length;
var diagonals = new Dictionary<int, List<int>>();
for (var i = 0; i < m; i++)
{
for (var j = 0; j < n; j++)
{
int diagonalIndex = i + j;
if (!diagonals.ContainsKey(diagonalIndex))
{
diagonals[diagonalIndex] = new List<int>();
}
diagonals[diagonalIndex].Add(mat[i][j]);
}
}
var result = new List<int>();
foreach (var key in diagonals.Keys)
{
var diagonal = diagonals[key];
if (key % 2 == 0)
{
result.AddRange(diagonal);
}
else
{
diagonal.Reverse();
result.AddRange(diagonal);
}
}
return result.ToArray();
}
}
class Program
{
static void Main()
{
var Solution = new Solution();
int[][] mat1 = new int[][]{
new int[]{1,2,3},
new int[]{4,5,6},
new int[]{7,8,9}
};
Console.WriteLine(string.Join(", ", Solution.FindDiagonalOrder(mat1)));
}
}