基礎練習 回形取數
時間限制:1.0s 記憶體限制:512.0MB
問題描述
回形取數就是沿矩陣的邊取數,若目前方向上無數可取或已經取過,則左轉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
析:看起來挺簡單,隻要按照它的要求輸出,就可以了,主要是判斷在拐彎的時候,隻要前面已經出界,或者是已經走過了,就左拐,如果還走過,再左拐,總能夠全部走完,但是Java 實在是太慢了,尤其是輸入和輸出,以至于我一直都是 90 ,後來加了一個輸出外挂,才 100,由于輸入外挂比輸出要長,是以不愛寫,但是C++ 是真的快,幾乎就是 0 ms
代碼如下:
import java.util.*;
import java.io.*;
public class Main{
public static int [][]a;
public static int []dr = {1, 0, -1, 0};
public static int []dc = {0, 1, 0, -1};
public static int n, m;
public static boolean isIn(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
public static void main(String []args){
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
m = cin.nextInt();
a = new int[n+5][m+5];
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
a[i][j] = cin.nextInt();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
out.print(a[0][0]);
a[0][0] = -1;
int idx = 0, r = 0, c = 0, cnt = 0;
while(++cnt < m * n){
while(true){
int x = r + dr[idx];
int y = c + dc[idx];
if(isIn(x, y) && a[x][y] != -1){
out.print(" " + a[x][y]);
a[x][y] = -1;
r = x; c = y;
break;
}
++idx;
if(idx >= 4) idx -= 4;
}
}
out.println();
out.flush();
}
}