码迷,mamicode.com
首页 > 编程语言 > 详细

#2019120700022 蛇形填充数组

时间:2019-12-07 10:27:28      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:main   names   print   scan   rtc   iostream   ++   tco   algorithm   

\(Way1\)

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
int a[21][21];
int n;
int main(){
    memset(a,0,sizeof(a));
    scanf("%d",&n);
    int x=1,y=n;
    a[x][y]=1;//一定要赋初值
    int now=1;
    while(now<n*n){
        while(x+1<=n&&!a[x+1][y]) a[++x][y]=++now;
        while(y-1>=1&&!a[x][y-1]) a[x][--y]=++now;
        while(x-1>=1&&!a[x-1][y]) a[--x][y]=++now;
        while(y+1<=n&&!a[x][y+1]) a[x][++y]=++now;
//顺序不能乱
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            printf("%4d ",a[i][j]);
        }
        printf("\n");
    }
    return 0;
}

\(Way2\)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
#define N 1010
int a[N][N];
int row,col,op=0,startRow,endRow,startCol,endCol;
int main( ){
    cin>>row>>col;
    for(int i=0;i<row;i++){
        for(int j=0;j<col;j++){
            scanf("%d",&a[i][j]);
        }
    }
    startRow=0;startCol=0;
    endRow=row-1;endCol=col-1;
    for(op=0;op<4;op++){
        while(startRow<=endRow&&startCol<=endCol){
        //对于每个op都有方向和起始终止位置
            if(op==0){
                for(int j=startCol;j<=endCol;j++){
                    printf("%d\n",a[startRow][j]);
                    }
                startRow++;
                }
            if(op==1){
                for(int i=startRow;i<=endRow;i++){
                    printf("%d\n",a[i][endCol]);
                }
                endCol--;
            }
            if(op==2){
                for(int j=endCol;j>=startCol;j--){
                    printf("%d\n",a[endRow][j]);
                }
                endRow--;
            }
            if(op==3){
                for(int i=endRow;i>=startRow;i--){
                    printf("%d\n",a[i][startCol]);
                }
                startCol++;
            }
            op=(op+1)%4;
            //使op在0,1,2,3之间循环
            }
        }
        return 0;
    }

#2019120700022 蛇形填充数组

标签:main   names   print   scan   rtc   iostream   ++   tco   algorithm   

原文地址:https://www.cnblogs.com/liuziwen0224/p/12000571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!