SDUSTOJ 1184
来源:互联网 发布:mac卡住了结束程序 编辑:程序博客网 时间:2024/05/29 11:19
题目
Description
将1~n*n填入一个n*n的矩阵中,并要求成为蛇形。蛇形即是从右上角开始向下,向左,向上,向右,循环填入数字。
比如n=5时矩阵为:
13 14 15 16 1
12 23 24 17 2
11 22 25 18 3
10 21 20 19 4
9 8 7 6 5
Input
输入有多行,每行为一个整数n(1<=n<=50),每组答案用空行隔开。
Output
输出一个n*n的矩阵,n行n列每个数字用一个空格隔开,不能有多余空格。
Sample Input
5
Sample Output
13 14 15 16 1
12 23 24 17 2
11 22 25 18 3
10 21 20 19 4
9 8 7 6 5
思路
紫书上讲过这个蛇形填数的题目
从1开始依次填写。设“笔”的坐标为(x,y),则一开始x=0,y=n-1,即第0行,第n-1列(行列的范围是0~n-1,没有第n列)。“笔”的移动轨迹是:下,下,下,左,左,左,上,上,上,右,右,下,下,左,上。总之,先是下,到不能填为止,然后是左,接着是上,最后是右。“不能填”是指再走就出界(例如4→5),或者再走就要走到以前填过的格子(例如12→13)。如果把所有格子初始化为0,就能很方便地加以判
AC代码
#include <stdio.h>#include <string.h>#include <stdlib.h>#define maxn 50+10int a[maxn][maxn];void putarray( int s[maxn][maxn], int n ){ for( int i = 0; i < n; i++) { for( int j = 0; j < n; j++) { if( j != 0 ) printf(" "); printf("%d", a[i][j]); } puts(""); }}int main(){ int n, x, y, t = 0; int num = 0; while( ~scanf("%d", &n) ) { if( ++num != 1 ) puts(""); memset(a, 0, sizeof(a)); x = 0, y = n-1; t = a[x][y] = 1; while(t < n*n) { while(x + 1 < n && !a[x+1][y]) a[++x][y] = ++t; while(y - 1 >= 0 && !a[x][y-1]) a[x][--y] = ++t; while(x - 1 >= 0 && !a[x-1][y]) a[--x][y] = ++t; while(y + 1 < n && !a[x][y+1]) a[x][++y] = ++t; } putarray(a,n); } return 0;}
阅读全文
0 0
- SDUSTOJ 1184
- SDUSTOJ
- SDUSTOJ
- SDUSTOJ 1466
- SDUSTOJ 1334
- SDUSTOJ T1581 Average Number
- SDUSTOJ T1587 YES! YOU CAN!
- [SDUSTOJ 1450]捡石子游戏
- SDUSTOJ-说好的点呢
- SDUSTOJ Problem F: 一元二次方程类
- SDUSTOJ Problem D: 时间类的构造和输出
- SDUSTOJ Problem E: 时间类的成员读写
- SDUSTOJ Problem H: 稀疏矩阵的表示和运算
- Problem H: 稀疏矩阵的表示和运算 SDUSTOJ
- SDUSTOJ Problem A: 平面上的点——Point类 (I)
- SDUSTOJ Problem A: 平面上的点——Point类 (I)
- SDUSTOJ Problem B: 平面上的点——Point类 (II)
- SDUSTOJ Problem C: 平面上的点——Point类 (III)
- 【tarjan思想 && 离线处理】Codeforces Round #436 (Div. 2) F
- 【挖坟贴】听听一周前专家对比特币未来的评价
- 连接数据库localhost和127.0.0.1的区别
- HIbernate创建表插入中文会乱码
- 架构漫谈(四):如何做好架构之架构切分
- SDUSTOJ 1184
- Python中的支持向量机SVM的使用(有实例)
- newcoder Wannafly挑战赛6 E-双拆分数(打表+构造)
- 架构漫谈(三):如何做好架构之识别问题
- zzb学习体系-java基础篇
- VM Guest与Host之间的通信
- 9种高性能可用高并发的技术架构
- Webstorm常用快捷键
- Sublime Text 3简单安装插件与主题