N*N数组插入数字

来源:互联网 发布:数据备份软件 编辑:程序博客网 时间:2024/05/18 00:37
/*12341213145111615610987*/

public static void nnArray(int num) {int direction = 0;int[][] arr = new int[num][num];int row = 0;int col = 0;for (int i = 1; i <= num * num; i++) {switch (direction) {case 0:if (col < num && arr[row][col] == 0) {arr[row][col] = i;col++;} else {col--;row++;i--;direction = 1;}break;case 1:if (row < num && arr[row][col] == 0) {arr[row][col] = i;row++;} else {row--;col--;i--;direction = 2;}break;case 2:if (col > -1 && arr[row][col] == 0) {arr[row][col] = i;col--;} else {col++;row--;i--;direction = 3;}break;case 3:if (row > 0 && arr[row][col] == 0) {arr[row][col] = i;row--;} else {row++;col++;i--;direction = 0;}break;default:break;}}for (int i = 0; i < arr.length; i++) {for (int j = 0; j < arr[i].length; j++) {System.out.print(arr[i][j] + "\t");}System.out.println("\n");}}
以螺旋方式向二位数组中插入数字,switch判断方向改变。                                             
0 0
原创粉丝点击