7.打印回形数
题目简介
题目链接:https://www.nowcoder.com/practice/2d47abf176f7486db0d707088404db8a
题目描述
回形数是一个矩阵输出,从矩阵的左上角往右开始打印数字0,遇到矩阵边界时,顺时针90方向继续打印,并数字增长1,如此类推直到把矩阵填满,输入一个整形宽和高单位,每输出一个数字,占用1单位宽高空间,根据入参打印出对应的回形数
输入描述:
矩阵的宽高
输出描述:
回字形的矩阵
示例1
输入
8 3
输出
00000000
34444441
22222221
说明
顺时针从0开始
题目分析
1.此题是顺时针打印矩阵的相似类型题。
2.回形数矩阵输出的打印方向分别是:从左到右、从上到下、从右到左、从下到上。因此,定义四个边界:左、右、上、下。
3.for循环遍历行走的方向。
4.根据边界范围判断是否打印完成。
5.我最近一直用js刷题,发现js刷题的弊端就是输入输出,牛客网虽然提供了js V8的输入输出,但是对于特定的格式输出还是比较困难,因此使用C语言实现。
#include<stdio.h>
int main(){
int width,height;
scanf("%d %d",&width,&height);
if(height <= 0 || width <= 0)
return 0;
int start = 0;
int arr[10][10];
int left = 0;
int right = width - 1;
int top = 0;
int bottom = height - 1;
int f = 0;
while (left<=right && top<=bottom) {
//从左到右
for (int i = left; i <= right; i++) {
arr[top][i] = f;
}
f++;
if (top < bottom ) {
//从上到下
for (int i = top + 1; i <= bottom; i++) {
arr[i][right] = f;
}
f++;
if (left < right) {
//从右到左
for (int i = right - 1; i >= left; i--) {
arr[bottom][i] = f;
}
f++;
}
if (top < bottom) {
// 从下到上
for (int i = bottom - 1; i > top; i--) {
arr[i][left] = f;
}
f++;
}
}
left++;
right--;
top++;
bottom--;
}
for(int i = 0; i < height; i++){
for(int j = 0; j< width; j++)
printf("%d",arr[i][j]);
printf("\n");
}
return 0;
}