题解 | 回型矩阵
回型矩阵
https://www.nowcoder.com/practice/36d5dfddc22c4f5b88a5b2a9de7db343
#include <stdio.h> int main() { int n; scanf("%d",&n); int arr[19][19] = {0}; int left = 0; int right = n - 1; int top = 0; int bottom = n -1 ; int num = 1; while(top <= bottom&&left <= right) { //从左到右 for(int i = left ; i <= right ; i++) { arr[top][i] = num++; } top++; // 从上到下 if(left <= right) { for(int j = top; j<=bottom;j++) { arr[j][right] = num++; } right--; } //从右到左 if(left<=right) { for(int g = right;g >= left; g--) { arr[bottom][g] = num++; } bottom--; } //从下到上 if(top <= bottom) { for(int l = bottom; l >=top;l--) { arr[l][left] = num++; } left++; } } for(int i = 0 ; i < n; i++) { for(int j = 0; j < n; j++) { printf("%d ",arr[i][j]); } printf("\n"); } return 0; }
主要还是设置边界,然后就是注意每次边界改变后要进行一个判断,防止越界