逆序输出螺旋字符矩阵(三种方法)
生活随笔
收集整理的這篇文章主要介紹了
逆序输出螺旋字符矩阵(三种方法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種
**相當于從一個點慢慢遍歷,每遍歷一個點就設為一個負數或大數(不與)題目的數據重復就好** #include<iostream> #include<algorithm>using namespace std;int a[300][300];int main() {int n, m;while (cin >> m >> n){for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)cin >> a[i][j];if (m == 1)for (int i = 0; i < n; i++)cout << a[0][i];{int count = n*m;int x = -1, y = -1;while (count){for (x = x + 1, y = y + 1; y < m && a[y][x]!=0; y++){cout << a[y][x];count--;a[y][x] = 0;}for (x = x + 1, y = y - 1; x < n && a[y][x]!=0; x++){cout << a[y][x];count--;a[y][x] = 0;}for (x = x - 1, y = y - 1; y >= 0 && a[y][x]!=0; y--){cout << a[y][x];count--;a[y][x] = 0;}for (x = x - 1, y = y + 1; x >= 0 && a[y][x]!=0; x--){cout << a[y][x];count--;a[y][x] = 0;}}}}return 0; }不過有一個缺點是,行列過大時會超時
## 第二種 **我們開始設置四個變量用這四個變量的變化來輸出,**代碼如下:(內有解釋)
#include <iostream> #include <string> #include<algorithm> using namespace std;int main() {int m, n;int a[101][101];while (cin >> n >> m){for (int i = 0; i < n; i++){for (int j = 0; j < m; j++)cin >> a[i][j];}if (n == 1)//特判一下{for (int i = 0; i < m; i++)cout << a[0][i];}else if (m == 1){for (int i = 0; i < n; i++)cout << a[i][0];}else{int z = 0, y = m - 1;//列int s = 0, x = n - 1;//行while (1)//死循環,循環中有結束的條件{for (int i = s; i <= x; i++){cout << a[i][z];}z++;if (z > y || s > x)//當你的小的列數與行數,比大的大時說明就可以結束了,不清楚的可以寫寫看break;for (int i = z; i<= y; i++){cout << a[x][i];}x--;if (z > y || s > x)break;for (int i = x; i >= s; i--){cout << a[i][y];}y--;if (z > y || s > x)break;for (int i = y; i >= z; i--){cout << a[s][i];}s++;if (z > y || s > x)break;}}cout << endl;}return 0; }第三種
通用方法,在應對往四個方向移動時可以設置方向數組
逆時針:
dx[4]={1,0,-1,0};
dy[4]={0,1,0,-1};
順時針:
dx[4]={0,1,0,1};
dy[4]={1,0,-1,0};
所以代碼如下:
#include<iostream> #include<algorithm> #include<cstring> int dx[4] = { 1,0,-1,0 };//逆時針 int dy[4] = { 0,1,0,-1 }; using namespace std;int main() {int n, m;char s[102][102];while(cin >> n >> m){memset(s, 0, sizeof(s));//清零int count = n * m;for (int i = 1; i <= n; i++)for (int j = 1; j <= m; j++)cin >> s[i][j];int d = 0, x = 1, y = 1;while (count){cout << s[x][y];s[x][y] = 0;count--;if (s[x + dx[d]][y + dy[d]] == 0)d = (d + 1) % 4;x = x + dx[d];y = y + dy[d];}cout << endl; } return 0; }總結
以上是生活随笔為你收集整理的逆序输出螺旋字符矩阵(三种方法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: string s.substr()的用法
- 下一篇: 二叉树(BST)之创建二叉搜索树