回型取数

问题描述
  回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
输入格式
  输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
输出格式
  输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
样例输入
3 3
1 2 3
4 5 6
7 8 9
样例输出
1 4 7 8 9 6 3 2 5
样例输入
3 2
1 2
3 4
5 6
样例输出
1 3 5 6 4 2

 1 import java.util.Scanner; 
 2 public class Test__25 {//可能会超时
 3         public static void main(String[] args) {  
 4       
 5             Scanner sc = new Scanner(System.in);  
 6             int m = sc.nextInt();  
 7             int n = sc.nextInt();  
 8             int[][] a = new int[m][n];  
 9             for (int i = 0; i < m; i++) {  
10                 for (int j = 0; j < n; j++) {  
11                     a[i][j] = sc.nextInt();  
12       
13                 }  
14       
15             }  
16             int tot = 0, x = -1, y = 0;  
17             while(tot<m*n){
18                 while(x+1<m && a[x+1][y]!=-1){
19                     System.out.print(a[++x][y]+" ");
20                     a[x][y] = -1;
21                     tot++;
22                 }
23                 while(y+1<n && a[x][y+1]!=-1){
24                     System.out.print(a[x][++y]+" ");
25                     a[x][y] = -1;
26                     tot++;
27                 }
28                 while(x-1>=0 && a[x-1][y]!=-1){
29                     System.out.print(a[--x][y]+" ");
30                     a[x][y] = -1;
31                     tot++;
32                 }
33                 while(y-1>=0 && a[x][y-1]!=-1){
34                     System.out.print(a[x][--y]+" ");
35                     a[x][y] = -1;
36                     tot++;
37                 }
38             }
39         }
40 }
原文地址:https://www.cnblogs.com/czy960731/p/6666266.html