今天,听人讲起了今年微软的面试题,其中有一道就是让你输出一个螺旋型的矩阵。一时兴起就写了一个,贴在这里晒一晒吧!
- #include<iostream>
- #include<iomanip>
- using namespace std;
- #define n 5 //矩阵行数
- #define m 10 //矩阵列数
- int main()
- {
- int a[n][m];
- int counter = 1;
- int i = 0;
- int j = 0;
- int k = 0;
- int l = 0;
- int s = 0;
- for(i = 0; i < n; i++) //初始化矩阵的值
- {
- for(j = 0; j < m; j++)
- {
- a[i][j] = 0;
- }
- }
- for(i = 0; i < n; i++)
- {
- for(j = i; j < m - i; j++)//赋值上横一线
- {
- if(a[i][j] == 0) //判断是否已被赋值
- {
- a[i][j] = counter;
- counter++;
- }
- }
- for(k = i + 1; k < n - i; k++)//赋值右竖一线
- {
- if(a[k][j - 1] == 0)
- {
- a[k][j - 1] = counter;
- counter++;
- }
- }
- for(l = j - 2; l >= i; l--)//赋值下横一线
- {
- if(a[k - 1][l] == 0)
- {
- a[k - 1][l] = counter;
- counter++;
- }
- }
- for(s = k - 2; s > i; s--)//赋值左竖一线
- {
- if(a[s][l + 1] == 0)
- {
- a[s][l + 1] = counter;
- counter++;
- }
- }
- }
- for(i = 0; i < n; i++) //输出矩阵
- {
- for(j = 0; j < m; j++)
- {
- cout<< setw(3) << a[i][j] << " ";
- }
- cout << endl;
- }
- return 0;
- }
- mini@mini-ThinkPad-T420:~/unixtest$ ./a.out
- 1 2 3 4 5 6 7 8 9 10
- 26 27 28 29 30 31 32 33 34 11
- 25 44 45 46 47 48 49 50 35 12
- 24 43 42 41 40 39 38 37 36 13
- 23 22 21 20 19 18 17 16 15 14
阅读(444) | 评论(0) | 转发(0) |