C++ 蛇形矩陣
阿新 • • 發佈:2019-02-09
#include<iostream> #define MAXROW 4 #define MAXCOL 4 using namespace std; //轉圈列印矩陣 //注意矩陣形狀:1、行向量 2、列向量 3、普通矩陣 void printEdge(int m[][MAXCOL],int tR,int tC,int dR, int dC) { //如果是行向量 if(tR == dR) { for(int i=tC;i<=dC;i++) { cout<<m[tR][i]<<"\t"; } } //如果是列向量 else if(tC == dC) { for(int i=tR;i<=dR;i++) cout<<m[i][tC]<<"\t"; } //如果是普通矩陣 else { int curC = tC; int curR = tR; while(curC != dC) { cout<<m[tR][curC]<<"\t"; curC++; } while(curR != dR) { cout<<m[curR][dC]<<"\t"; curR++; } while(curC != tC) { cout<<m[dR][curC]<<"\t"; curC--; } while(curR != tR) { cout<<m[curR][tC]<<"\t"; curR--; } } cout<<endl; } void printSpecialMatrix(int m[][MAXCOL]) { cout<<"==============NEW MATRIX=============="<<endl; int tR=0,tC=0; int dR=MAXROW-1,dC=MAXCOL-1; while(tR <= dR && tC <= dC) printEdge(m,tR++,tC++,dR--,dC--); } void printMatrix(int m[][MAXCOL]) { cout<<"==============OLD MATRIX=============="<<endl; for(int i=0;i<MAXROW;i++) { for(int j=0;j<MAXCOL;j++) cout<<m[i][j]<<"\t"; cout<<endl; } } int main() { int matrix[MAXROW][MAXCOL] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; printMatrix(matrix); printSpecialMatrix(matrix); return 0; }