面试题4(剑指)-螺旋打印矩阵
题目
n阶矩阵,螺旋打印出来
思路
需要控制:1.边界 2.方向
使用一个二维数组存放数据,数组初始化为0,数组共有n平方个元素,因为是从1开始,所以元素的值是从1到n×n。每次填入一个数字判断一次方向和边界
实现
package lms.algorithm.offer; //螺旋打印矩阵 public class SpiralMatrix { public static int[][] createMatrix(int n){ int[][] matrix = new int[n][n]; int right = 1, down = 2, left = 3, up = 4; int direction = right; int numb = n * n; int i = 0, j = 0; for (int p = 1; p <= numb; p++){ matrix[i][j] = p; if (direction == right){ if (j + 1 < n && matrix[i][j + 1] == 0){ j++; }else { i++; direction = down; continue; } } if (direction == down){ if (i + 1 < n && matrix[i+1][j] == 0){ i++; }else { j--; direction = left; continue; } } if (direction == left){ if (j - 1 >= 0 && matrix[i][j-1] == 0){ j--; }else { i--; direction = up; continue; } } if (direction == up){ if (i - 1 >= 0 && matrix[i-1][j] == 0){ i--; }else { j++; direction = right; continue; } } } return matrix; } public static void main(String[] args) { int[][] n = createMatrix(6); for (int i=0;i<n.length;i++){ for (int j=0;j<n[i].length;j++){ System.out.printf("%d\t",n[i][j]); } System.out.println(""); } } }
运行结果