程序员面试题精选100题(51)-顺时针打印矩阵

题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字

例如:如果输入如下矩阵:

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。


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;
 }
}


你可能感兴趣的:(程序员)