蛇形矩阵

蛇形矩阵

/** * @author clydelou * */ public class SnakeMatrix { /** * @param args */ public static int snake(int n) { if (n <= 0) { System.out.println("error"); return 0; } else { int value = 1; int i = 0, j = 0; int[][] array = new int[n][n]; boolean[][] flag = new boolean[n][n]; int t = n * n; while (value <= t) { if (i == 0 && j == 0) { array[i][j] = value++; flag[i][j] = true; i++; } if (j == 0 && i > 0 && i < n - 1) { if (flag[i - 1][j + 1]) { array[++i][j] = value++; flag[i][j] = true; } while (i != 0) { array[--i][++j] = value++; flag[i][j] = true; } } if (i == 0 && j > 0 && j < n - 1) { if (flag[i + 1][j - 1]) { array[i][++j] = value++; flag[i][j] = true; } while (j != 0) { array[++i][--j] = value++; flag[i][j] = true; } } if (i == n - 1 && j >= 0 && j < n - 1) { if (flag[i - 1][j + 1]) { array[i][++j] = value++; flag[i][j] = true; } while (j != n - 1) { array[--i][++j] = value++; flag[i][j] = true; } } if (j == n - 1 && i >= 0 && i < n - 1) { if (flag[i + 1][j - 1]) { array[++i][j] = value++; flag[i][j] = true; } while (i != n - 1) { array[++i][--j] = value++; flag[i][j] = true; } } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { System.out.print(array[i][j] + "/t"); } System.out.println(); } return 1; } } public static void main(String[] args) { // TODO Auto-generated method stub snake(7); } }


运行结果:

1 2 6 7 15 16 28 3 5 8 14 17 27 29 4 9 13 18 26 30 39 10 12 19 25 31 38 40 11 20 24 32 37 41 46 21 23 33 36 42 45 47 22 34 35 43 44 48 49

 

你可能感兴趣的:(蛇形矩阵)