[WikiOI] 2.2.2 蛇形矩阵

[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 array int **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; } } // init i = j = n / 2; array[i][j] = 1; // write data bool 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]; // completed if(i < 0 || i == n || j < 0 || j == n){ completed = true; break; } array[i][j] = a++; } // change forward steps if(cnt % 2 == 0){ k++; } // change direction d++; d %= 4; } // output result int 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; }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值