1 2 3
4 5 6
7 8 9
1 2
3 4
5 6
1 3 5 6 4 2
一次提交就是滿分嘻嘻
/**
*
*/
package 基礎練習;
import java.util.Scanner;
/**
* @author Administrator 問題描述
* 回形取數就是沿矩陣的邊取數,若當前方向上無數可取或已經取過,則左轉90度。一開始位於矩陣左上角,方向向下。 輸入格式
* 輸入第一行是兩個不超過200的正整數m, n,表示矩陣的行和列。接下來m行每行n個整數,表示這個矩陣。 輸出格式
* 輸出只有一行,共mn個數,爲輸入矩陣回形取數得到的結果。數之間用一個空格分隔,行末不要有多餘的空格。
*/
public class 回型取數 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] a = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
int tot = 0, x = -1, y = 0;
while (tot < m * n) {
while (x + 1 < m && a[x + 1][y] != -1) {
System.out.print(a[++x][y]+" ");
a[x][y] = -1;
++tot;
}
while (y + 1 < n && a[x][y + 1] != -1) {
System.out.print(a[x][++y]+" ");
a[x][y] = -1;
++tot;
}
while (x - 1 >= 0 && a[x - 1][y] != -1) {
System.out.print(a[--x][y]+" ");
a[x][y] = -1;
++tot;
}
while (y - 1 >= 0 && a[x][y - 1] != -1) {
System.out.print(a[x][--y]+" ");
a[x][y] = -1;
++tot;
}
}
// for (int i = 0; i < m; i++) {
// for (int j = 0; j < n; j++) {
// System.out.println(a[i][j]);
//
// }
// }
}
}