问题描述
我正在尝试用二维数组制作螺旋。但是我缺少最后一个元素,如图所示。
我试图在while循环中设置各种条件以在一个循环后停止算法,但我做不到,因此我变得疯狂。主要算法代码如下:
// height is always bigger than width by 1
char [][] blankGrid = new char [height][width];
int dir = 0;
int top = 0;
int bottom = height-1;
int left = 0;
int right = width-1;
//draw digit spiral
while(top <= bottom && left <= right ) {
//RIGHT
if (dir == 0) {
for (int i = left; i <= right; i++) {
blankGrid[top][i] = '0';
if(left != 0 )blankGrid[top ][i-1] = '0';
System.out.println(" DIR = 0 Position changed: "+ top + "," + i);
}
top += 2;
dir++;
//DOWN
} else if (dir == 1) {
for (int i = top; i <= bottom; i++) {
blankGrid[i][right] = '1';
blankGrid[i-1][right] = '1';
System.out.println(" DIR = 1 Position changed: "+ top + "," + i );
}
right -= 2;
dir++;
//LEFT
}else if (dir == 2) {
for (int i = right; i >= left; i--) {
blankGrid[bottom][i] = '2';
blankGrid[bottom][i+1] = '2';
System.out.println(" DIR = 2 Position changed: "+ bottom + "," + i);
}
bottom -= 2;
dir++;
//UP
}else if (dir == 3) {
for (int i = bottom; i >= top ; i--) {
blankGrid[i][left] = '3';
blankGrid[i+1][left] = '3';
System.out.println(" DIR = 3 Position changed: "+ top + "," + i);
}
left += 2;
dir = 0;
}
}
// display grid
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j ++){
System.out.printf("%c",blankGrid[i][j]);
}
System.out.println();
}
我想要的输出:
我尝试了以下方法:
while(top <= bottom +/- 1 && left <= right +/- 1 )
while(top <= bottom +/- 2 && left <= right +/- 2)
while(bottom - top >= 0 && right - left >=0 )
还有更多,但结果与上图相同。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)