順時針列印矩形列表

來源:互聯網
上載者:User

標籤:

問題:輸入一個矩陣,按照從外向裡以順時針的順序依次列印出每一個數字,例如,如果輸入如下矩陣: 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.

方法1

public static ArrayList<Integer> printMatrix(int [][] matrix) {
int n = matrix[0].length;
int m = matrix.length;
if(m == 0 ) return null;
ArrayList<Integer> arr = new ArrayList<Integer>();

int circle = ((Math.min(n, m)-1)/2)+1;//層數
for(int i=0;i<circle;i++){
for(int j = i;j<n-i;j++){//從左往右
arr.add(matrix[i][j]);
}
for(int j=i+1;j<m-i;j++){//從上到下
arr.add(matrix[j][n-i-1]);
}
for(int j=n-i-1-1;j>=i&&(m-i-1!=i);j--){//從右至左
arr.add(matrix[m-i-1][j]);
}
for(int j=m-i-1-1;j>i&&(n-i-1!=i);j--){//從下到上
arr.add(matrix[j][i]);
}

}
return arr;

}

方法2:

public static ArrayList<Integer> printMatrix1(int [][] matrix) {
int n = matrix[0].length;
int m = matrix.length;
if(m == 0 ) return null;
ArrayList<Integer> arr = new ArrayList<Integer>();

int top = 0,left = 0,right = n-1,bottom =m-1;
while(top<=bottom && left<=right){
for(int i = left;i <=right;i++){//從左至右
arr.add(matrix[top][i]);
}
for(int i = top+1;i<=bottom;i++){//從上到下
arr.add(matrix[i][right]);
}
if(top!=bottom){
for(int i = right-1;i>=left;i--){//從右至左
arr.add(matrix[bottom][i]);
}
}
if(left!=right){
for(int i=bottom-1;i>top;i++){//從下到上
arr.add(matrix[i][left]);
}
}
top++;
left++;
right--;
bottom--;

}

return arr;

}

順時針列印矩形列表

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.