当前位置:网站首页>Serpentine matrix

Serpentine matrix

2022-07-05 04:11:00 Learning KL & TK

 

#include"bits/stdc++.h"

using namespace std;
int s[105][105];
int n;
void init(){
	 for(int i=0;i<n;i++){
        for(int j=0;j<n;j++)
            printf("%d ",s[i][j]);
        cout << endl;
    }
}
int main()
{
	cin >> n;
	int ans = 1; 
	int i = 0 , j = 0;
	s[0][0]=ans++;
	while(ans < n*n){
		//  Judge whether it is horizontal or vertical  
		if(j < n-1)
			j++;
		else 
			i++;
		
		s[i][j] = ans++;
		// The lower left  
		while(j>0 && i < n-1){
			j--;i++;
			s[i][j] = ans++;
		}
	//	 Judge whether it is horizontal or vertical  
		if(i < n-1)
			i++;
		else 
			j++;
		s[i][j] = ans++;
		// The upper right 
		while(i>0 && j<n-1){
			j++;i--;
			s[i][j] = ans++;
		} 
	}
	init();
	
	return 0;
}

原网站

版权声明
本文为[Learning KL & TK]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050407459246.html