笔试代码题--米哈游--顺时针打印矩阵字母
题目要求:输入矩阵的行和列,然后顺时针顺出打印字母A-Z。
输入 1:
1 1
输出1:
A A
输入2:
5 3
输出2:
A B C D E
L M N O F
K J I H G
输入3:
5 3
输出3:
A B C D E
L M N O F
K J I H G
输入4:
10 12
输出4:
解题思路:
和顺时针打印矩阵是很像的:https://mp.csdn.net/editor/html/108602165,可看这个博客。
首先输出的顺序如下图:
先将26个字母用字符串string保存起来,然后用index下标位一步一步移动,然后输出字母,注意用%26将从头再开始输出。
注意if(top != bottom),if(left != right),这两个条件是为了避免重复输出。
代码如下:
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int m,n;
cin >> m >> n;
vector<vector<char>> vec1(m,vector<char>(n));
string s = "ABCDEFGHIJKLIMNOPQRSTUVWXYZ";
int index = 0;
int left = 0,top = 0,right = n - 1 ,bottom = m-1;
while(left <= right && top <= bottom)
{
for(int i = left;i <= right; i++)
{
vec1[top][i]= s[index++];
index %= 26;
}
for(int i = top + 1;i <= bottom; i++)
{
vec1[i][right]= s[index++];
index %= 26;
}
if(top != bottom)
{
for(int i = right-1;i >= left; --i)
{
vec1[bottom][i]= s[index++];
index %= 26;
}
}
if(left != right)//下到上
{
for(int i = bottom - 1;i > top; --i)//注意i > top,不是>=,原因可看图解
{
vec1[i][left]= s[index++];
index %= 26;
}
}
left++,top++,right--,bottom--;
}
//打印二维数组
for(int i = 0; i < m;i++)
{
for(int j = 0;j < n;j++)
{
cout << vec1[i][j] << " ";
}
cout << endl;
}
return 0;
}
结果1:
结果2:
结果3: