2 solutions

  • 1
    @ 2024-10-29 17:58:05
    #include<bits/stdc++.h>
    using namespace std;
    int main(){
    	int n,s[10][10],sum=0,j=0;
    	int a[10][10] = {0};
    	int dx[] = {0,1,0,-1};
    	int dy[] = {1,0,-1,0};
    	int dir = 0;
    	int x = 0, y = -1;
    	cin >> n;
    	for(int i=1;i<=n*n;i++){
    		int nx = x + dx[dir];
    		int ny = y + dy[dir];
    		if (nx >= n || ny >= n || nx < 0 || ny < 0 || a[nx][ny] != 0) {
    			dir = (dir + 1) % 4;
    			nx = x + dx[dir];
    			ny = y + dy[dir];
    		}
    		
    		
    		a[nx][ny] = i;
    		x = nx, y = ny;
    	}
    	for (int i = 0; i < n; i++) {
    		for (int j = 0; j < n; j++) {
    			cout << setw(3) << a[i][j];
    		}
    		cout << '\n';
    	} 
    }
    

    Information

    ID
    416
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    4
    Tags
    (None)
    # Submissions
    91
    Accepted
    40
    Uploaded By