每天一道劍指offer-順時針列印矩陣
- 2019 年 10 月 4 日
- 筆記
前言
今天的題目 每天的題目見github(看最新的日期): https://github.com/gzc426 具體的題目可以去牛客網對應專題去找。
昨天的題解
題目
每天一道劍指offer-順時針列印矩陣 來源:牛客網對應專題
題目詳述
輸入一個矩陣,按照從外向里以順時針的順序依次列印出每一個數字,例如,如果輸入如下4 X 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.
題目詳解
思路
- 按照順時針列印矩陣,這裡的話我用了一個變數count,來記錄遍歷的數目,當count如果小於等於二維矩陣的數目的話,說明沒有遍歷完成,直到count達到二維數組的數目。
- 程式碼中的left,right,bottom,top解讀。left代表最左的一層,top代表最頂的一層,bottom代表最低的一層,right代表最右的一層,舉個例子,比如最頂的層top,每當遍歷完最上面的一層,那麼就top++,比如最底層bottom每當遍歷完最低一層就bottom–,這樣下去肯定會出現top和bottom相遇的情況,也就是全部都遍歷完了
程式碼
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> resultList = new ArrayList<>(); int cols = matrix[0].length; int rows = matrix.length; int left=0,top=0,bottom=rows-1,right=cols-1; int count = 0;//計數,count如果達到數組的全部個數,那麼結束。 while(count < cols*rows) { for(int i=left;i<=right;i++)//從左往右進行遍歷,第一層 {//left是目前最左邊的那個邊界,right是目前最右邊的邊界 resultList.add(matrix[top][i]); count++; if(count >= cols*rows) return resultList; } top++;//遍歷完目前的最頂層,那麼top就到下一層 for(int i=top;i<=bottom;i++) {//從上往下進行遍歷,top是目前最上的邊界,bottom是目前最下的邊界 resultList.add(matrix[i][right]); count++; if(count >= cols*rows) return resultList; } right--;//遍歷完最右邊的邊界,那麼right就減一,到下一個最右邊邊界 for(int i=right;i>=left;i--) {//從右到左,和上面同理 resultList.add(matrix[bottom][i]); count++; if(count >= cols*rows) return resultList; } bottom--; for(int i=bottom;i>=top;i--) {//從下到上,和上面同理。 resultList.add(matrix[i][left]); count++; if(count >= cols*rows) return resultList; } left++; } return resultList; } }
程式碼截圖(避免亂碼)