#2019120700022 蛇形填充数组

\(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;
	}
posted @ 2019-12-07 09:05  刘子闻  阅读(119)  评论(0)    收藏  举报