螺旋矩阵的一个实现

看到了一个要实现下面这个图形的一个螺旋矩阵,就自己写了一个,不足的地方,大家给改正下!!!!

1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19


public static void main(String[] args) {
luo(10, 10);
}

static void luo(int row, int col) {
int varRow = row;
int varCol = col;
int sum = row * col;

// 数组中的行下标
int rowNum = 0;
// 数组中的列下标
int colNum = 0;
// 左边的最小列
int minCol = -1;
// 上边的最小行
int minRow = 0;

// 每一个元素中的值,从 1 开始累加
int value = 1;
// 计算方向 开始是向右的
int position = POSITION.RIGHT.code;

int[][] array = new int[row][col];

for (int i = 0; i < sum;) {
// 向右进行赋值
if (position == POSITION.RIGHT.code && colNum < varCol) {
array[rowNum][colNum] = value;
i++;
value++;
colNum++;
}
else if (position == POSITION.RIGHT.code && colNum == varCol) {
position = POSITION.DOWN.code;
colNum--;
rowNum++;
}
// 向下进行赋值
else if (position == POSITION.DOWN.code && rowNum < varRow) {
array[rowNum][colNum] = value;
i++;
value++;
rowNum++;
}
else if (position == POSITION.DOWN.code && rowNum == varRow) {
position = POSITION.LEFT.code;
colNum--;
rowNum--;
}
// 向左进行赋值
else if (position == POSITION.LEFT.code && colNum > minCol) {
array[rowNum][colNum] = value;
i++;
value++;
colNum--;
}
else if (position == POSITION.LEFT.code && colNum == minCol) {
position = POSITION.UP.code;
colNum++;
rowNum--;

}
// 向上进行赋值
else if (position == POSITION.UP.code && rowNum > minRow) {
array[rowNum][colNum] = value;
i++;
value++;
rowNum--;
}
// 在结束了一个从右到下, 从下到左,从左到上的过程后,总行数要减少,总列数要减少,上边的最小行数增加,左边的最小列数增加
else if (position == POSITION.UP.code && rowNum == minRow) {
position = POSITION.RIGHT.code;
colNum++;
rowNum++;
minRow++;
minCol++;
varCol--;
varRow--;

}
}

for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.printf("%-5s", array[i][j]);
}
System.out.println();
}

}

// 定义计算的方向,包括有 上 下 左 右 四个方向
enum POSITION {
RIGHT(0), DOWN(1), LEFT(2), UP(3);
private int code;

POSITION(int code) {
this.code = code;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值