問題描述
回形取數就是沿矩陣的邊取數,若當前方向上無數可取或已經取過,則左轉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
import java.util.Scanner;
//回形取數
public class Main{
static int cnt=0;
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine();
int [][]arr = new int[n][m];
int [][]vis = new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
arr[i][j] = sc.nextInt();
}
int x=-1,y=0;
while(cnt < n*m){
while(x+1 < n && vis[x+1][y] == 0){
System.out.print(arr[++x][y]+" ");
vis[x][y] = 1;
cnt=cnt+1; //或者++cnt;
}
while(y+1 <m && vis[x][y+1] == 0){
System.out.print(arr[x][++y]+" ");
vis[x][y] = 1;
++cnt;
}
while(x-1 >-1 && vis[x-1][y] == 0){
System.out.print(arr[--x][y]+" ");
vis[x][y] = 1;
++cnt;
}
while(y-1 >-1 && vis[x][y-1] == 0){
System.out.print(arr[x][--y]+" ");
vis[x][y] = 1;
++cnt;
}
}
}
}
剛開始使用dfs解決,由於有幾組數據太大就爆棧了。還是用while解決安穩。