蛇形填数

来源:互联网 发布:cfd软件下载 编辑:程序博客网 时间:2024/05/21 14:06

蛇形填数
时间限制:3000 ms | 内存限制:65535 KB
难度:3
描述
在n*n方陈里填入1,2,…,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
输入
直接输入方陈的维数,即n的值。(n<=100)
输出
输出结果是蛇形方陈。
样例输入
3
样例输出
7 8 1
6 9 2
5 4 3
来源
算法经典
题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=33

问题分析:
典型的排版问题。分析蛇形填数的特点,发现是从外圈先填,然后在填内圈,一直填到最中心。
因此题目的问题转为对圈的抽象。
对于n*n的方阵,一共有(n+1)/2圈,从最外圈开始到最内圈,对于每一个圈layer=1,2,…,(n+1)/2,右上角坐标为(layer-1,n-layer)。
对每个圈的填充过程如下图所示:
这里写图片描述

因此就将整个蛇形填充分解为对每个圈的填充,每个圈又是由其右上角坐标和圈的长度length决定的,因此由每个圈的右上角坐标和圈的长度length即可对整个圈进行填充。

代码:

#include <iostream>#include <stdio.h> #include <string.h>#include <math.h>#include <vector>#include <queue>#include <stack>#include <map>#include <string>#include <algorithm>#define N 101using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */int n;int rec[N][N];void output(){        //输出        for(int i=0;i<n;i++) {            int j;            for(j=0;j<n-1;j++){                cout<<rec[i][j]<<" ";            }            cout<<rec[i][j];            cout<<endl;        }        return;}int main(int argc, char** argv) {    while(cin>>n){        int count=1; //计数器         //最中间的圈右上角坐标         int bound_x= (n+1)/2-1;        int bound_y= n/2;        //从第一圈开始,一直到 (n+1)/2圈为止         for(int layer=1;layer<=(n+1)/2;layer++){            //每一圈中右上角的坐标            int x=layer-1;             int y=n-layer;            //每圈的长度            int length=n-2*(layer-1);            //填充右边            for(int i=x;i<=x+length-1;i++){                rec[i][y]=count++;            }            //output();            //填充下边            for(int i=y-1;i>=y-length+1;i--){                rec[x+length-1][i]=count++;            }                //output();            //填充左边            for(int i=x+length-2;i>=x;i--){                rec[i][y-length+1]=count++;            }                //output();            //填充上边             for(int i=y-length+1+1;i<=y-1;i++){                rec[x][i]=count++;            }        }        output();    }    return 0;}

代码分析:
算了,不分析了。先给妹子弄实验哇。