Interview question 18: clockwise print matrix

Source: Internet
Author: User

Analysis:Think of a matrix as several circles, and print a circle of the matrix with a loop.

# Include "stdafx. H "# include <iostream> using namespace STD; void printmatrixincircle (INT ** narr, int rows, int columns, int nstart) {int nendx = columns-1-nstart; int nendy = rows-1-nstart; // print a row from left to right (INT I = nstart; I <= nendx; I ++) {cout <narr [nstart] [I] <"" ;}// print a column from top to bottom if (nendy> nstart) {for (Int J = nstart + 1; j <= nendy; j ++) {cout <narr [J] [nendx] <"";}} // print a line from right to left if (nendy> nstart & nendx> nstart) {for (int t = nEndX-1; t> = nstart; t --) {cout <narr [nendy] [T] <";}}// print a column from bottom to top if (nendy-1> nstart & nendx> nstart) {for (INT n = nEndY-1; n> = nstart + 1; n --) {cout <narr [N] [nstart] <"";}}} // print the matrix clockwise. The number of rows is rows, and the number of columns is columnsvoid printmatrixclockwisely (INT ** narr, int rows, int columns) {If (narr = NULL | rows <= 0 | columns <= 0) {return;} int nstart = 0; while (rows> (nstart * 2) & columns> (nstart * 2) {printmatrixincircle (narr, rows, columns, nstart); nstart ++ ;}} int _ tmain (INT argc, _ tchar * argv []) {int nmatrix1 [4] [4] = {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}; int ** PP1 = new int * [4]; for (INT I = 0; I <4; I ++) {PP1 [I] = nmatrix1 [I];} printmatrixclockwisely (PP1, 4, 4); cout <Endl; int nmatrix2 [1] [4] = {1, 2, 3, 4}; int ** PP2 = new int * [1]; for (INT I = 0; I <1; I ++) {PP2 [I] = nmatrix2 [I];} printmatrixclockwisely (PP2, 1, 4); cout <Endl; int nmatrix3 [4] [1] = {1}, {2}, {3}, {4}; int ** PP3 = new int * [4]; for (INT I = 0; I <4; I ++) {PP3 [I] = nmatrix3 [I];} printmatrixclockwisely (PP3, 4, 1 ); cout <Endl; int nmatrix4 [2] [5] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int ** PP4 = new int * [2]; for (INT I = 0; I <2; I ++) {PP4 [I] = nmatrix4 [I];} printmatrixclockwisely (PP4, 2, 5 ); cout <Endl; System ("pause"); Return 0 ;}

Running result:


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.