zoukankan      html  css  js  c++  java
  • #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("
    ");
    	}
    	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
    ",a[startRow][j]);
    					}
    				startRow++;
    				}
    			if(op==1){
    				for(int i=startRow;i<=endRow;i++){
    					printf("%d
    ",a[i][endCol]);
    				}
    				endCol--;
    			}
    			if(op==2){
    				for(int j=endCol;j>=startCol;j--){
    					printf("%d
    ",a[endRow][j]);
    				}
    				endRow--;
    			}
    			if(op==3){
    				for(int i=endRow;i>=startRow;i--){
    					printf("%d
    ",a[i][startCol]);
    				}
    				startCol++;
    			}
    			op=(op+1)%4;
    			//使op在0,1,2,3之间循环
    			}
    		}
    		return 0;
    	}
    
    要做就做南波万
  • 相关阅读:
    2
    1
    nginx隐藏版本号
    全面对比主流 .NET 报表控件 (转)
    前端的发展和未来趋势
    NPM初学者指南 (转)
    一文解读MySQL事务
    如何高效的学习技术
    重新统一的 .NET平台-.NET 5
    为啥要有微服务?啥是微服务?
  • 原文地址:https://www.cnblogs.com/liuziwen0224/p/12000571.html
Copyright © 2011-2022 走看看