逆序输出螺旋字符矩阵(三种方法)
生活随笔
收集整理的這篇文章主要介紹了
逆序输出螺旋字符矩阵(三种方法)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第一種
**相當(dāng)于從一個(gè)點(diǎn)慢慢遍歷,每遍歷一個(gè)點(diǎn)就設(shè)為一個(gè)負(fù)數(shù)或大數(shù)(不與)題目的數(shù)據(jù)重復(fù)就好** #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; }不過(guò)有一個(gè)缺點(diǎn)是,行列過(guò)大時(shí)會(huì)超時(shí)
## 第二種 **我們開(kāi)始設(shè)置四個(gè)變量用這四個(gè)變量的變化來(lái)輸出,**代碼如下:(內(nèi)有解釋)
#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)//死循環(huán),循環(huán)中有結(jié)束的條件{for (int i = s; i <= x; i++){cout << a[i][z];}z++;if (z > y || s > x)//當(dāng)你的小的列數(shù)與行數(shù),比大的大時(shí)說(shuō)明就可以結(jié)束了,不清楚的可以寫(xiě)寫(xiě)看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; }第三種
通用方法,在應(yīng)對(duì)往四個(gè)方向移動(dòng)時(shí)可以設(shè)置方向數(shù)組
逆時(shí)針:
dx[4]={1,0,-1,0};
dy[4]={0,1,0,-1};
順時(shí)針:
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 };//逆時(shí)針 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; }總結(jié)
以上是生活随笔為你收集整理的逆序输出螺旋字符矩阵(三种方法)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: string s.substr()的用法
- 下一篇: 二叉树(BST)之创建二叉搜索树