ACM编程比赛入门题目之蛇形矩阵 CodeVS/wikioi 1160

来源:互联网 发布:什么是网络超市? 编辑:程序博客网 时间:2024/06/05 07:36
<span style="font-family: 'Hiragino Sans GB W3', 'Hiragino Sans GB', Arial, Helvetica, simsun, u5b8bu4f53; background-color: rgb(238, 238, 238);">http://codevs.cn/problem/1160/</span>

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

输入描述 Input Description
n(即n行n列)

输出描述 Output Description
n+1行,n行为组成的矩阵,最后一行为对角线数字之和

样例输入 Sample Input
3

样例输出 Sample Output

5 4 3
6 1 2
7 8 9
25

#include <iostream>using namespace std;typedef int ElemType;ElemType n, **p;void Init() {int x, y;int Center = (n + 1) / 2, data = 1;x = y = Center;for (int i = 1; i <= Center; i++) {//上移 减左移 减while (y < Center + i)//右移p[x][y++] = data++;if (y > n)break;while (x > Center - i) //上移p[x--][y] = data++;while (y > Center - i)//左移p[x][y--] = data++;while (x < Center + i)//下移p[x++][y] = data++;}}int main() {cin >> n;if (n % 2 == 0)return 0;p = new ElemType*[n + 1];for (int i = 1; i <= n; i++)p[i] = new ElemType[n + 1];Init();for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++) {cout << p[i][j] << ' ';}cout << endl;}int sum = 0;for (int i = 1; i <= n; i++)sum += p[i][i];for (int i = 1; i <= n; i++)sum += p[i][n - i + 1];cout << sum - p[(n + 1) / 2][(n + 1) / 2] << endl;system("pause >nul");return 0;}
0 0
原创粉丝点击