LeetCode,leetcodeoj

來源:互聯網
上載者:User

LeetCode,leetcodeoj
題目描述:


Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.


For example,
Given the following matrix:


[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].


從例子可以看出,需要做的是從矩陣的第一個元素為起始,沿外環向內依次遍曆,最後列印出結果。


思路:
擷取矩陣的長寬,設需要走n圈,則n = Min(寬度,高度)/2。
從左上節點為起始開始遍曆,走到最右的最後一個元素開始向下走,走到最後向左走,最後向上走。走了一圈,需要把座標往內+1。
需要考慮剛好處於矩陣中間線的情況。


實現代碼:






public class Solution {    public IList<int> SpiralOrder(int[,] matrix) {   if(matrix == null){return new List<int>();}var result = new List<int>();var rowLen = matrix.GetLength(0);var len = matrix.GetLength(1);if(rowLen == 1){for(var i =0 ;i < len; i++){result.Add(matrix[0,i]);}return result;}if(len == 1){for(var i =0 ;i < rowLen; i++){result.Add(matrix[i,0]);}return result;}var minLen = Math.Min(rowLen,len);var cycleCount = minLen % 2 == 0 ? minLen/2 : (minLen + 1) / 2;var c = 0;for(var i = 0;i < cycleCount; i++){if(c == len-c-1){for(var k = c;k < rowLen - c; k++){result.Add(matrix[k, c]);}c++;continue;}// stick row to top, column : [c,len-c-1]for(var top = c; top < len-c - 1; top++){result.Add(matrix[c,top]);}// stick column to right, row : [c,rowLen-c-1]for(var right = c; right < rowLen-c - 1; right ++){result.Add(matrix[right, len-c-1]);}// stick row to bottom, column : [len-c-1, c]for(var down = len-c -1; down > c; down --){result.Add(matrix[rowLen-c-1, down]);}// stick column to left, row : [len-c-1, c]for(var left = rowLen-c - 1; left > c; left --){result.Add(matrix[left, c]);}c++;}return result;    }     }


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.