Offoffer: clockwise print matrix, and offoffer Matrix

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.