Matrix算法(1)

实现以下Matrix算法:
[img]http://dl.iteye.com/upload/attachment/464717/88dd7581-e00c-3d2f-b77a-44aa604da6ea.jpg[/img]

import java.io.IOException;

public class MatrixTest_1 {
public static void main(String[] args) throws IOException {
int[][] data = generateMatrix(5);
for (int i = 0; i < data.length; i++) {
for (int m = 0; m < data[i].length; m++) {
if (data[i][m] == 0)
System.out.print("\t");
else
System.out.print(data[i][m] + "\t");
}
System.out.println();
}
}

private static int[][] generateMatrix(int n) {

int[][] ret = new int[n][n];

int maxValue = n * n;

int directionStatus = 1;

int rowIndex = 0;
int colIndex = 0;

for (int i = 1; i <= maxValue; i++) {

ret[rowIndex][colIndex] = i;
if (rowIndex == n - 1)
break;
if (directionStatus == 1) {
if (rowIndex < n - 1) {
rowIndex++;
} else {
colIndex++;
}
directionStatus = 2;
} else if (directionStatus == 2) {
rowIndex--;
colIndex++;
if (rowIndex == 0) {
directionStatus = 3;
}
if (colIndex == n - 1) {
directionStatus = 3;
}
} else if (directionStatus == 3) {
if (colIndex < n - 1) {
colIndex++;
} else {
rowIndex++;
}
directionStatus = 4;
} else if (directionStatus == 4) {
rowIndex++;
colIndex--;
if (colIndex == 0) {
directionStatus = 1;
}
if (rowIndex == n - 1) {
directionStatus = 1;
}
}
}
return ret;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值