日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

逆序输出螺旋字符矩阵(三种方法)

發布時間:2025/3/19 编程问答 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 逆序输出螺旋字符矩阵(三种方法) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

第一種

**相當于從一個點慢慢遍歷,每遍歷一個點就設為一個負數或大數(不與)題目的數據重復就好** #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; }

總結

以上是生活随笔為你收集整理的逆序输出螺旋字符矩阵(三种方法)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。