标签:更新 ble color 移动 oid false ace std str
Problem:
“之”字形打印矩阵【题目】 给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵,
例如: 1 2 3 4 5 6 7 8 9 10 11 12
“之”字形打印的结果为:1,2,5,9,6,3,4,7,10,11,8,12
【要求】 额外空间复杂度为O(1)
Solution:
使用A,B两个坐标,初始值为(0,0),(0,0),A,B的连线为之字形的斜线
A移动方向为向右走,B移动方向为向下走,A到最右边了就向下走,B到最下面了就向右走
使用一个bool值,判断是向右上方方向遍历A-B直线,还是向左下角方向遍历A-B直线
A
|
B- 1 2 3 4
5 6 7 8
9 1 0 5
Code:
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 void ZiPrint(const T arr, const int x, const int y) 7 { 8 int Ax = 0, Ay = 0;//初始化A,B的坐标 9 int Bx = 0, By = 0; 10 bool flag = true;//true为右上方方向遍历, false为左下角方向遍历 11 12 while (Ax <= x-1 && Ay <= y-1)//A到右下角就遍历完毕 13 { 14 if(flag)//右上方方向遍历 15 { 16 int Tx = Bx, Ty = By; 17 while (Tx >= Ax || Ty <= Ay) 18 { 19 cout << arr[Tx][Ty] << " "; 20 Tx -= 1; 21 Ty += 1; 22 } 23 flag = false; 24 } 25 else//向左下角方向遍历 26 { 27 int Tx = Ax, Ty = Ay; 28 while (Tx <= Bx || Ty >= By) 29 { 30 cout << arr[Tx][Ty] << " "; 31 Tx += 1; 32 Ty -= 1; 33 } 34 flag = true; 35 } 36 //更新A,B 37 if (Ay < y - 1) 38 Ay += 1; 39 else 40 Ax += 1; 41 42 if (Bx < x - 1) 43 Bx += 1; 44 else 45 By += 1; 46 47 } 48 cout << endl; 49 50 } 51 52 void Test() 53 { 54 int aa[3][4] = { 1,2,3,4,5,6,7,8,9,10,11,12 }; 55 ZiPrint(aa, 3, 4); 56 }
标签:更新 ble color 移动 oid false ace std str
原文地址:https://www.cnblogs.com/zzw1024/p/10989199.html