java编程题,输入一个正整数,按如下形式输出

输入7,则12345672425262728298234041424330922394849443110213847464532112037363534331219181... 输入7,则
1 2 3 4 5 6 7
24 25 26 27 28 29 8
23 40 41 42 43 30 9
22 39 48 49 44 31 10
21 38 47 46 45 32 11
20 37 36 35 34 33 12
19 18 17 16 15 14 13
展开
 我来答
czhang5265
2011-03-30
知道答主
回答量:24
采纳率:0%
帮助的人:11.5万
展开全部
public class TestPrint {
public static void main(String[] args) {
Matrix m = new Matrix(15);
m.compute();
System.out.print(m);

}
}

class Matrix {
private enum Direction {
LEFT, RIGHT, UP, DOWN
};

int rowCount;
int[][] data;

public Matrix(int rowCount) {
this.rowCount = rowCount;
this.data = new int[rowCount][rowCount];
for (int i = 0; i < this.rowCount; i++) {
for (int j = 0; j < this.rowCount; j++) {
data[i][j] = -1;
}
}
}

public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < this.rowCount; i++) {
for (int j = 0; j < this.rowCount; j++) {
sb.append(data[i][j] + ", ");
}
sb.append("\n");
}
return sb.toString();
}

public void compute() {
int length = rowCount * rowCount + 1;
int counter = 1;
int rowStartBound = 0;
int columnStartBound = 0;
int rowEndBound = rowCount-1;
int columnEndBound = rowCount-1;
int currentRow = rowStartBound;
int currentColumn = columnStartBound;
Direction dir = Direction.RIGHT;
while (counter < length) {
data[currentRow][currentColumn] = counter;

switch (dir) {
case RIGHT:
currentColumn++;
if (currentColumn > columnEndBound) {
currentColumn--;
currentRow++;
dir = Direction.DOWN;
columnEndBound--;
}
break;
case LEFT:
currentColumn--;
if (currentColumn < columnStartBound) {
currentColumn++;
currentRow--;
dir = Direction.UP;
columnStartBound++;
}
break;
case UP:
currentRow--;
if (currentRow < rowStartBound+1) {
currentRow++;
currentColumn++;
dir = Direction.RIGHT;
rowStartBound++;
}
break;
case DOWN:
currentRow++;
if (currentRow > rowEndBound) {
currentRow--;
currentColumn--;
dir = Direction.LEFT;
rowEndBound--;
}
break;
}
counter++;
}
}
}
hai131214
2011-03-30 · TA获得超过508个赞
知道小有建树答主
回答量:542
采纳率:0%
帮助的人:94.4万
展开全部
算法问题。。 不是难的
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式