*【九度OJ1362】|【劍指offer20】順時針打印矩陣

題目描述: java

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每個數字,例如,若是輸入以下矩陣: 測試

1 2 3 4 this

5 6 7 8 spa

9 10 11 12 code

13 14 15 16 it

則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. io

輸入:

輸入可能包含多個測試樣例,對於每一個測試案例, class

輸入的第一行包括兩個整數m和n(1<=m,n<=1000):表示矩陣的維數爲m行n列。 import

接下來的m行,每行包括n個整數,表示矩陣的元素,其中每一個元素a的取值範圍爲(1<=a<=10000)。 im

輸出:

對應每一個測試案例,輸出一行,

按照從外向裏以順時針的順序依次打印出每個數字,每一個數字後面都有一個空格。

樣例輸入:
4 4
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

注:運行超時

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
 
public class Main {
 
    public int top = 0;
    public int bottom;
    public int left = 0;
    public int right;
    public int[][] a;
    public int length;
    private int count = 0;
 
    public Main(int bottom, int right, int[][] a) {
        this.bottom = bottom;
        this.right = right;
        this.a = a;
        this.length = (bottom + 1) * (right + 1);
    }
 
    public void print() {
        if (left > right && top > bottom)
            return;
        if (top <= bottom) {
            for (int i = left; i <= right; i++) {
                p(a[top][i]);
            }
            top++;
        }
        if (left <= right && right >= 0) {
            for (int j = top; j <= bottom; j++) {
                p(a[j][right]);
            }
            right--;
        }
        if (top <= bottom && bottom >= 0) {
            for (int m = right; m >= left; m--) {
                p(a[bottom][m]);
            }
            bottom--;
        }
        if (left <= right) {
            for (int n = bottom; n >= top; n--) {
                p(a[n][left]);
            }
            left++;
        }
        print();
    }
 
    public void p(int value) {
        if (count < length - 1) {
            System.out.print(value + " ");
        } else if (count == length - 1) {
            System.out.println(value + " ");
        }
        count++;
    }
 
    public static void main(String[] args) throws IOException {
        StreamTokenizer st = new StreamTokenizer(new BufferedReader(
                new InputStreamReader(System.in)));
        while (st.nextToken() != StreamTokenizer.TT_EOF) {
            int row = (int) st.nval;
            st.nextToken();
            int col = (int) st.nval;
            int[][] a = new int[row][col];
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    st.nextToken();
                    a[i][j] = (int) st.nval;
                }
            }
            Main m = new Main(row - 1, col - 1, a);
            m.print();
        }
    }
}
/**************************************************************
    Problem: 1391
    User: aqia358
    Language: Java
    Result: Time Limit Exceed
****************************************************************/
相關文章
相關標籤/搜索