【筆試題解】順時針打印矩陣

題目鏈接:順時針打印矩陣(筆試版)


備註:《劍指offer》原題,但是在線筆試版本由於輸入格式&時間限制,有許多細節需要調整。


爲了避免超時的tips:
(1)不能用Scanner而改用BufferedReader——這裏要記住BufferedReader的使用模板&注意事項:
-----1.0 需要import的有三個類,也可以直接寫:

import java.io.*;

-----1.1 使用BufferedReader必須在main函數後面寫`throws IOException`
-----1.2 new一個BufferedReader的代碼爲

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

-----1.3 用br讀取一行輸入的整數,存儲在數組裏要這樣寫:

String[] s = br.readLine().split(" "); //以空格作爲分隔,讀入的每一個整數先作爲一個字符串存儲在數組中
int[] array = new int[n];
for(int i = 0; i < n; i++)
    array[i] = Integer.parseInt(s[i]); //再把每個“字符串”形式的整數轉換爲int型


-----1.4 用br讀取多行輸入,要寫 while(br.ready()) 作爲循環條件


(2)打印矩陣之前不用ArrayList存儲所有元素,而用StringBuilder存儲


AC代碼如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while(br.ready()) {
            String[] s = br.readLine().split(" ");
            int m = Integer.parseInt(s[0]);
            int n = Integer.parseInt(s[1]);
            if(m == -1 && n == -1) break;
            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++) {
                String[] temp = br.readLine().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(temp[j]);
            }
            printMatrix(matrix, m, n);
        }
    }
    private static void printMatrix(int[][] mat, int rows, int cols) {
        if(mat == null || rows == 0 || cols == 0) return;
        StringBuilder sb = new StringBuilder();
        int min = Math.min(rows, cols);
        for(int s = 0; 2*s < min; s++) {
            int endRow = rows-1-s;
            int endCol = cols-1-s;
            for(int j = s; j <= endCol; j++) //直接打印第一行
                sb.append(mat[s][j]+",");
            if(endRow > s) { //存在第二行的條件
                for(int i = s+1; i <= endRow; i++)
                    sb.append(mat[i][endCol]+",");
                if(endCol > s) { //存在第三行的條件
                    for(int j = endCol-1; j >= s; j--)
                        sb.append(mat[endRow][j]+",");
                    if(endRow > s+1) { //存在第四行的條件
                        for(int i = endRow-1; i > s; i--)
                            sb.append(mat[i][s]+",");
                    }
                }
            }
        }
        //打印
        System.out.println(sb.substring(0,sb.length()-1)); //記得不要打印出最後的逗號
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章