螺旋矩阵

N*N螺旋矩阵

public class SpiralMatrix { public static int spiral(int n) { if (n <= 0) { System.out.println("error"); return 0; } else { int direction_index = 0; boolean[][] flag = new boolean[n][n]; int[][] array = new int[n][n]; int i = 0, j = 0; int value = 1; int s = 0; int t = n * n; while (s < t) { if (direction_index == 0 && !flag[i][j]) { flag[i][j] = true; s++; array[i][j] = value++; if (s == t) break; if (j == n - 1 || flag[i][j + 1]) { direction_index = 1; i++; } else { j++; } } if (direction_index == 1 && !flag[i][j]) { flag[i][j] = true; s++; array[i][j] = value++; if (i == n - 1 || flag[i + 1][j]) { direction_index = 2; j--; } else { i++; } } if (direction_index == 2 && !flag[i][j]) { flag[i][j] = true; s++; array[i][j] = value++; if (j == 0 || flag[i][j - 1]) { direction_index = 3; i--; } else { j--; } } if (direction_index == 3 && !flag[i][j]) { flag[i][j] = true; s++; array[i][j] = value++; if (i == 0 || flag[i - 1][j]) { direction_index = 0; j++; } else { i--; } } } 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 spiral(6); } }

你可能感兴趣的:(螺旋矩阵)