自学内容网 自学内容网

华为机考真题 -- 螺旋数字矩阵

题目描述:

疫情期间,小明隔离在家,百无聊赖,在纸上写数字玩。他发明了一种写法:给出数字 个数 n 和行数 m(0 < n ≤ 999,0 < m ≤ 999),从左上角的 1 开始,按照顺时针螺旋向内写方式,依次写出 2,3...n,最终形成一个 m 行矩阵。小明对这个矩阵有些要求:
1.每行数字的个数一样多
2.列的数量尽可能少
3.填充数字时优先填充外部
4.数字不够时,使用单个*号占位

输入描述:

两个整数,空格隔开,依次表示 n、m


输出描述:

符合要求的唯一矩阵

示例1:

输入
9 4


输出
1 2 3
* * 4
9 * 5
8 7 6
说明:9 个数字写成 4 行,最少需要 3 列

示例2:

输入
3 5


输出
1
2
3
*
*
说明:3 个数字写 5 行,只有一列,数字不够用*号填充

示例3:

输入
120 7


输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 19
45 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 63 20
44 83 114 115 116 117 118 119 120 * * * * * * 99 64 21
43 82 113 112 111 110 109 108 107 106 105 104 103 102 101 100 65 22
42 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 23
41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24

C++源码:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

void fillSpiralMatrix(int n, int m) {
int column = (n + m - 1) / m;
vector<vector<string>> mapGame(m, vector<string>(column, "*"));
vector<int> dx = { 0, 1, 0, -1 }, dy = { 1, 0, -1, 0 };

int directX = 0, directY = 0, dir = 0;
for (int i = 1; i <= n; ++i) { 
mapGame[directX][directY] = to_string(i);
if (i == n)
break;

while (true) { 
int nx = directX + dx[dir], ny = directY + dy[dir];
if (nx < 0 || nx >= m || ny < 0 || ny >= column || mapGame[nx][ny] != "*") {
dir = (dir + 1) % 4;
}
else {
directX = nx;
directY = ny;
break;
}
}
}

int i = 0;
while (i < m) {
int j = 0;
while (j < column) {
cout << mapGame[i][j] << " ";
++j;
}
cout << endl;
++i;
}
}

signed main() {
int n, m;
cin >> n >> m;
fillSpiralMatrix(n, m);

system("pause");
return 0;
}


原文地址:https://blog.csdn.net/qq_25360769/article/details/140313899

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!