当前位置: 代码迷 >> 综合 >> [WikiOI] 2.2.2 蛇形矩阵
  详细解决方案

[WikiOI] 2.2.2 蛇形矩阵

热度:62   发布时间:2023-12-09 06:00:36.0

[Problem]

小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字,请输出该n行n列正方形矩阵以及其的对角线数字之和.

[Solution]

#include <iostream> using namespace std;int direct[4][2] = { {0, 1}, {-1, 0}, {0, -1}, {1, 0}};/*** main*/ int main(){int n, i, j, k = 1;cin >> n;// create arrayint **array = new int*[n];for(i = 0; i < n; ++i){array[i] = new int[n];for(j = 0; j < n; ++j){array[i][j] = 0;}}// initi = j = n / 2;array[i][j] = 1;// write databool completed = false;int d = 0, a = 2, cnt = 0;while(!completed){cnt++;for(int b = 0; b < k; ++b){i += direct[d][0];j += direct[d][1];// completedif(i < 0 || i == n || j < 0 || j == n){completed = true;break;}array[i][j] = a++;}// change forward stepsif(cnt % 2 == 0){k++;}// change directiond++;d %= 4;}// output resultint sum = 0;for(i = 0; i < n; ++i){for(j = 0; j < n; ++j){if(i == j || i+j == n-1){sum += array[i][j];}cout << array[i][j] << " ";}cout << endl;}cout << sum << endl;return 0; }