*【九度OJ1362】|【剑指offer20】顺时针打印矩阵

题目描述:

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:

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.

输入:

输入可能包含多个测试样例,对于每个测试案例,

输入的第一行包括两个整数m和n(1<=m,n<=1000):表示矩阵的维数为m行n列。

接下来的m行,每行包括n个整数,表示矩阵的元素,其中每个元素a的取值范围为(1<=a<=10000)。

输出:

对应每个测试案例,输出一行,

按照从外向里以顺时针的顺序依次打印出每一个数字,每个数字后面都有一个空格。

样例输入:
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
****************************************************************/







你可能感兴趣的:(java,九度OJ1362,顺时针打印矩阵,剑指offer20)