对角线遍历
描述:https://leetcode.cn/leetbook/read/array-and-string/cuxq3/
错误代码
c语言代码⬇️
int* findDiagonalOrder(int** mat, int matSize, int* matColSize) {
int* ret = (int*)malloc(sizeof(int) * matSize * (*matColSize));
int idx = 0;
int row = 0;
int col = 0;
for (int i = 0; i <= matSize + (*matColSize); i++) {
if (i % 2 == 0) {
while (row >= 0 &&
row < matSize &&
col < *matColSize &&
col >= 0) {
ret[idx++] = mat[row][col];
row--;
col++;
}
//如果往右上角溢出
if (row < 0 && col == *matColSize) {
row = 1;
col = *matColSize - 1;
}
//如果在上边溢出
if (row < 0) {
row = 0;
}
//如果在右边溢出
if (col == *matColSize) {
col -= 1;
row += 2;
}
}
else {
while (row >= 0 &&
row < matSize &&
col < *matColSize &&
col >= 0) {
ret[idx++] = mat[row][col];
row++;
col--;
}
//如果在左下角溢出
if (row = matSize && col < 0) {
row = matSize - 1;
col = 1;
}
//如果在下边溢出
if (row = matSize) {
row -= 1;
col += 2;
}
//如果在左边溢出
if (col < 0) {
col += 1;
}
}
}
return ret;
}
错误原因:sir. 请不要在判断语句中将==写成=,这非常的不professional
通过代码
通过代码1⬇️
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findDiagonalOrder(int** mat, int matSize, int* matColSize, int* returnSize){
int* ret = (int*)malloc(sizeof(int) * matSize * (*matColSize));
*returnSize = matSize * (*matColSize);
int idx = 0;
int row = 0;
int col = 0;
for (int i = 0; i <= matSize + (*matColSize); i++) {
if (i % 2 == 0) {
while (row >= 0 &&
row < matSize &&
col < *matColSize &&
col >= 0) {
ret[idx++] = mat[row][col];
row--;
col++;
}
//如果往右上角溢出
if (row < 0 && col == *matColSize) {
row = 1;
col = *matColSize - 1;
}
//如果在上边溢出
if (row < 0) {
row = 0;
}
//如果在右边溢出
if (col == *matColSize) {
col -= 1;
row += 2;
}
}
else {
while (row >= 0 &&
row < matSize &&
col < *matColSize &&
col >= 0) {
ret[idx++] = mat[row][col];
row++;
col--;
}
//如果在左下角溢出
if (row == matSize && col < 0) {
row = matSize - 1;
col = 1;
}
//如果在下边溢出
if (row == matSize) {
row -= 1;
col += 2;
}
//如果在左边溢出
if (col < 0) {
col += 1;
}
}
}
return ret;
}
通过代码2⬇️
总结
总结:n