我正在尝试解决螺旋阶矩阵问题(https://leetcode.com/problems/spiral-matrix-ii/description/)
我已经解决了这个问题(几乎97%)。代码在第二层打印中失败。我在这里发布我的(Java)方法(生成矩阵的代码)。
感谢您的帮助。
public int[][] generateMatrix(int inputNumber) {
int[][] spiralMatrix = new int[inputNumber][inputNumber];
int totalElementCount = inputNumber * inputNumber;
int topMostLeft = 0;
int bottomMostLeft = 0;
int topMostRight = inputNumber -1;
int bottomMostRight = inputNumber -1;
int row = 0;
int column = 0;
int direction = 1;
for(int loopIndex = 0; loopIndex < totalElementCount ; loopIndex++) {
//System.out.println("\nDirection : "+direction + " loopIndex : "+loopIndex);
//Left to right
if(direction == 1) {
//System.out.println("row : " + row + " column : "+column + " topMostRight : "+topMostRight + " spiralMatrix[row][column] : "+spiralMatrix[row][column]);
if(column < topMostRight) {
if(spiralMatrix[row][column] == 0) {
spiralMatrix[row][column++] = loopIndex+1;
}
else {
//System.out.println("Inside else");
spiralMatrix[row][++column] = loopIndex+1;
}
/*System.out.println("row : " + row + " column : "+column + " topMostRight : "+topMostRight);
System.out.println("spiralMatrix[row][column++] :"+spiralMatrix[row][column]);*/
//column++;
}
else if(column == topMostRight) {
spiralMatrix[row][column] = loopIndex+1;
topMostRight--;
direction = 2;
}
}
//Top to Bottom
if(direction == 2) {
//System.out.println("row : "+row + " bottomMostRight : "+bottomMostRight);
if(row < bottomMostRight) {
spiralMatrix[row++][column] = loopIndex + 1;
}
else if(row == bottomMostRight) {
spiralMatrix[row][column] = loopIndex+1;
bottomMostRight--;
direction = 3;
}
}
//Right to left
if(direction == 3) {
//System.out.println("column : "+column + " bottomMostLeft : "+bottomMostLeft);
if(column > bottomMostLeft) {
spiralMatrix[row][column--] = loopIndex + 1;
}
else if(column == bottomMostLeft) {
spiralMatrix[row][column] = loopIndex+1;
bottomMostLeft--;
direction = 4;
}
}
//Bottom to top
if(direction == 4) {
//System.out.println("row : "+ row + " topMostLeft: "+topMostLeft);
if(row > topMostLeft) {
spiralMatrix[row--][column] = loopIndex+1;
}
else if (row == topMostLeft) {
topMostLeft++;
column++;
row++;
direction = 1;
//System.out.println("row : "+row + " column : "+column + " loopIndex : "+loopIndex);
spiralMatrix[row][column] = loopIndex + 1;
//System.out.println("row : " + row + " column : " + column + " spiralMatrix[row+1][matrix+1] is : "+spiralMatrix[row+1][column+1] + " spiralMatrix[row][column] "+spiralMatrix[row][column]);
}
}
}
return spiralMatrix;
}
示例输出:
1 2 3 4
12 13 15 5
11 0 16 6
10 9 8 7
答案 0 :(得分:0)
最后,
发现了问题。我错过了处理第二层/下一个连续层的功能,其中先前的层已经被填充了一些值。现在,添加一个检查。该代码正在为顺畅的流程而努力。现在,在其他情况下工作。