public class Solution { public int[] FindDiagonalOrder(int[,] matrix) { var row = matrix.GetLength(0); var col = matrix.GetLength(1); var upBound = row - 1 + col - 1; var ary = new int[row * col]; int i = 0; int j = 0; var index = 0; if (row == 1) { for (int m = 0; m < col; m++) { ary[index++] = matrix[0, m]; } return ary; } if (col == 1) { for (int m = 0; m < row; m++) { ary[index++] = matrix[m, 0]; } return ary; } var direction = true;// for (int k = 0; k <= upBound; k++)//对角线上的i,j之和 { if (i == 0 && j == 0) { ary[index++] = matrix[i, j]; j = 1; continue; } //结束点 if (i == row - 1 && j == col - 1) { ary[index++] = matrix[i, j]; break; } var EndJ = Math.Min(i, col - 1);//0 var EndI = Math.Min(j, row - 1);//1 while (i + j == k) { ary[index++] = matrix[i, j]; if ((direction && (j == 0 || i == row - 1)) || (!direction && (i == 0 || j == col - 1))) { if (direction) { i++; if (i > row - 1) { i = row - 1; j++; if (j > col - 1) { j = col - 1; } } } else { j++; if (j > col - 1) { j = col - 1; i++; if (i > row - 1) { i = row - 1; } } } direction = !direction; continue; } if (direction) { i++; if (i > row - 1) { i = row - 1; } j--; if (j < 0) { j = 0; } } else { j++; if (j > col - 1) { j = col - 1; } i--; if (i < 0) { i = 0; } } } } return ary; } }
https://leetcode.com/problems/diagonal-traverse/#/description
时间: 2024-10-07 05:26:56