旋轉數組
描述:
某個圖像通過一個整數組成的m*n矩陣表示,其中每個整數表示一個像素值。寫出一種方法,根據flag變量的值將圖像向右或者向左旋轉90°。如果flag值為0,則向左旋轉,如果flag為1,則向右旋轉。
函數rotatePictureMethod的輸入分別由矩陣matrix、矩陣的維度m和n以及flag的值組成。
函數應返回一個指向二維矩陣指針,該矩陣是按照flag值旋轉后的結果矩陣而動態分配的。
示例:
如果標志flag=1且m=3,n=3,
輸入矩陣
1 2 3
4 5 6
7 8 9
輸出矩陣
7 4 1
8 5 2
9 6 3
思路:
逆時針旋轉:
1 交換主對角線對稱的元素;
2 交換第i行和第n-1-i行;
順時針旋轉:
1 交換副對角線對稱的元素;
2 交換第i行和第n-1-i行;
原圖: 第一步操作后: 第二步操作后: 1 2 3 4 1 5 9 13 4 8 12 16
5 6 7 8 2 6 10 14 3 7 11 15
9 10 11 12 3 7 11 15 2 6 10 14
13 14 15 16 4 8 12 16 1 5 9 13
C++代碼:
#include <iostream>
using namespace std; void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } // 逆時針旋轉
void transpose(int a[][4], int n) { for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) swap(a[i][j], a[j][i]); for (int i = 0; i < n / 2; i++) for (int j = 0; j < n; j++) swap(a[i][j], a[n - 1 - i][j]); } // 順時針旋轉
void clockwise(int a[][4], int n) { for (int i = 0; i < n; i++) for (int j = 0; j < n - i; j++) swap(a[i][j], a[n - 1 - j][n - 1 - i]); for (int i = 0; i < n / 2; i++) for (int j = 0; j < n; j++) swap(a[i][j], a[n - 1 - i][j]); } int main(int argc, char** argv) { int a[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; cout << "原矩陣" << endl; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) cout << a[i][j] << " "; cout << endl; } cout << endl; transpose(a, 4); cout << "逆時針轉90度" << endl; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) cout << a[i][j] << " "; cout << endl; } cout << endl; int a2[4][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; cout << "原矩陣" << endl; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) cout << a2[i][j] << " "; cout << endl; } clockwise(a2, 4); cout << endl; cout << "順時針轉90度" << endl; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) cout << a2[i][j] << " "; cout << endl; } return 0; }
打印一個有規律的矩陣
描述:
給定一個整數n,以下列方式打印n行。
如果n=4,生成的排列將為:
1*2*3*4
9*10*11*12
13*14*15*16
5*6*7*8
函數squarePatternPrint的輸入應包括一個整數n(假設0<=n<=100)。不要從函數返回任何內容。使用cout打印所需的陣列。
各輸出行只能由“數字”和“*”組成,不應有空格。
有用的命令:cout可將內容打印到屏幕上。
思路:
如果n為偶數,就打印n/2行,如果n為奇數,就打印n/2+1行;
以n=4舉例,先打印1*2*3*4,把5壓進棧,5+n = 9,打印9*10*11*12,把13壓進棧,此時從棧頂讀取13,打印13*14*15*16,彈出棧頂元素13,繼續從棧頂讀取5,打印5*6*7*8,判斷此時棧內為空,end.
這種思路有些繁瑣,我覺得肯定有更好的思路,只是我沒想起來,如果你有更好的思路,歡迎評論!
C++代碼:
#include <iostream> #include <stack>
using namespace std; void sprint(int n) { stack<int> nums; int i = 1, j = 1, flag = 0; if (n % 2 == 0) flag = n / 2; else flag = n / 2 + 1; for (; i <= flag; i++) { for (int k = 0; k < n; k++) { if (j % n == 0) cout << j; else cout << j << "*"; j++; } nums.push(j); j = j + n; cout << endl; } if (n % 2 != 0) nums.pop(); while (!nums.empty()) { int top = nums.top(); nums.pop(); for (int k = 0; k < n; k++) { if (top % n == 0) cout << top; else cout << top << "*"; top++; } cout << endl; } } int main() { sprint(3); }
參考:
http://www.voidcn.com/article/p-wusaguhx-bbb.html
https://blog.csdn.net/qq_26525215/article/details/52076488