java编程--图表(四)回型矩阵
package com.neuedu.one;
import java.util.Scanner;
//回型矩阵
public class Ch5 {
/*
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15
二维数组a[8][8]
for 赋值
位置:i,j 1.j++ 2.i++ 3.j-- 4.i--
4轮
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入矩阵行数:");
int num = scanner.nextInt();
int[][] a = new int[num][num];
int i = 0;
int k = 1;
for (int m = 0; m < num / 2; m++) {// 4轮
for (int n = m; n < num - m; n++) { // 行
a[i][n] = k;
k++;
}
i++;
if (num - 2 * m > 2) {
for (int n = m + 1; n <= num - m - 2; n++) {// 列
a[n][num - m - 1] = k;
k++;
}
}
for (int n = num - m - 1; n >= m; n--) {
a[num - m - 1][n] = k;
k++;
}
if (num - 2 * m > 2) {
for (int n = num - m - 2; n >= m + 1; n--) {
a[n][m] = k;
k++;
}
}
}
for (int m = 0; m < a.length; m++) {
for (int j = 0; j < a[m].length; j++) {
System.out.print(a[m][j] + " ");
}
System.out.println();
}
}
}
----------------------------------------------------------------------------------------------------------------------------
package com.neuedu.one;
public class Ch6 {
/*回型矩阵
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15
根据方向的变化,通过列长度和初始化的值的变化,由外而内,逐个赋值写入
*/
static int length = 8;
static int[][] snake= new int[length][length];
static int value = 1;
static Direction lastDirection = Direction.Right;
static enum Direction{
Right,Down,Left,Up;
}
public static void initialArray(){//顺时针填充数字
int row = 0;
int col = 0;
for(int c = 0; c < length*length; c++) {//循环填充数字
snake[row][col] = value;
lastDirection = findDirection(row,col);//寻找下一步方向
switch (lastDirection) {
case Right:
col++;
break;
case Left:
col--;
break;
case Up:
row--;
break;
case Down:
row++;
break;
default:
System.out.println("error");
}
value++;
}
}
static Direction findDirection(int row,int col) {
//根据当前方向和当前位置,确定下一步方向
Direction direction = lastDirection;
switch (direction) {
case Right:
//如果到右边界或是右方已经填充过数字,则向下转弯
if((col == length-1)||(snake[row][col+1] != 0)) {
direction = direction.Down;
}
break;
case Down:
//如果到下边界或是下方已经填充过数字,则向左转弯
if((row == length-1)||(snake[row+1][col] != 0)) {
direction = direction.Left;
}
break;
case Left:
//如果到达左边界或是左边已经填充过数字,则向上转弯
if((col == 0)||(snake[row][col-1] != 0)) {
direction = direction.Up;
}
break;
case Up:
if(snake[row-1][col] != 0) {
direction = direction.Right;
}
break;
}
return direction;
}
public static void print(int[][] snake) {
for(int i = 0; i < length; i++) {
for(int j = 0; j < length; j++) {
System.out.print(snake[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
initialArray();//填充数组
print(snake);//打印数组
}
}