Offoffer: clockwise print matrix, and offoffer Matrix
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a? Rp = 1 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Enter a matrix and print each number in clockwise order from the external, for example, if you enter the following matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 the numbers 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10 are printed in sequence.
Ideas
First, we can draw the entire printing process on the paper. We can know that every time we take a circle, we need four cycles to complete this circle, to mark the headers and tails of the four loops, we can complete the entire printing process.
class Solution{public:vector<int> printMatrix(vector<vector<int> > a){vector<int> ans;int row = a.size();if(row==0)return ans;int col = a[0].size();int start = 0;while(col>start*2 && row>start*2){int endx = row-1-start,endy = col-1-start;int i;for(i = start; i<=endy; ++i)ans.push_back(a[start][i]);if(start<endx){for(i = start+1; i<=endx; ++i)ans.push_back(a[i][endy]);}if(start<endx && start<endy){for(i = endy-1; i>=start; --i)ans.push_back(a[endx][i]);}if(start<endx-1 && start<endy){for(i = endx-1; i>=start+1; --i)ans.push_back(a[i][start]);}++start;}return ans;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source