题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 例如:如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
这道题我在google,onsite的时候遇到了, 当时纠结了好久,因为不知道如何让object去变化的移动.这是考点1. switch + recursion
考点2是 如何证明你的想法是正确的,其实就是switch出来按顺序1,2,3,4,5 a[i]=k k++. 就可以了.
public class Car { private int x=0; private int y=-1; Direction direction = Direction.E; private int[][] arr ; //最小边界是变化的. private int minX=-1; private int minY=-1; private int maxX; private int maxY; public Car(int[][] arr){ maxX = arr.length; maxY = arr[0].length; this.arr=arr; } public void move(){ if(maxX==minX&&maxY==minY){ return; } switch(direction){ case N: if(x-1<=minX){ minY++; direction=Direction.E; }else{ x--; System.out.print(arr[x][y]+" "); } break; case E: if(y+1>=maxY){ minX++; direction=Direction.S; }else{ y++; System.out.print(arr[x][y]+" "); } break; case S: if(x+1>=maxX){ maxY--; direction=Direction.W; }else{ x++ ; System.out.print(arr[x][y]+" "); } break; case W: if(y-1<=minY){ maxX--; direction=Direction.N; }else{ y--; System.out.print(arr[x][y]+" "); } break; } move(); } public static void main(String[] args) { int[][] arr = new int[4][4]; int k=1; //验证部分. for(int i=0;i<4;i++){ for(int j=0;j<4;j++){ arr[i][j]=k; k++; } } //执行部分 Car c = new Car(arr); c.move();} enum Direction { N,E,S,W; }}