1 条题解

  • 0
    @ 2024-12-18 14:07:32

    C :

    #include<stdio.h>
    
    int main()
    {
    	int n,m,i,j,a;
    	int top,bottom,left,right;
    	int arr[100][100];
    	scanf("%d %d",&n,&m);
    	i=0;
    	j=0;
    	a=1;
    	top=0;
    	bottom=0;
    	left=0;
    	right=0;
    	while(top+bottom<n&&left+right<m)
    	{
    	    if(top+bottom<n)
    		{
    		    for(i=top,j=left;j<m-right;j++)
    			{
    			    arr[i][j]=a;
    				a++;
    			}
    			top++;
    		}
    		if(left+right<m)
    		{
    		    for(j=m-right-1,i=top;i<n-bottom;i++)
    			{
    			    arr[i][j]=a;
    				a++;
    			}
    			right++;
    		}
    	    if(top+bottom<n)
    		{
    		    for(i=n-bottom-1,j=m-right-1;j>=left;j--)
    			{
    			    arr[i][j]=a;
    				a++;
    			}
    			bottom++;
    		}
    		if(left+right<m)
    		{
    		    for(j=left,i=n-bottom-1;i>=top;i--)
    			{
    			    arr[i][j]=a;
    				a++;
    			}
    			left++;
    		}
    	}
    	
    	for(i=0;i<n;i++)
    	{
    	    for(j=0;j<m;j++)
    		{
    		    printf("%d ",arr[i][j]);
    		}
    		printf("\n");
    	}
    
    
        return 0;
    }
    

    C++ :

    #include <iostream>
    
    using namespace std;
    const int N = 105;
    
    int a[N][N];
    int n, m;
    
    int main() {
        cin >> n >> m;
    
        int left = 0, right = m - 1, top = 0, bottom = n - 1;
        int k = 1;
        while (left <= right && top <= bottom) {
            for (int i = left ; i <= right; i ++) {
                a[top][i] = k ++;
            }
            for (int i = top + 1; i <= bottom; i ++) {
                a[i][right] = k ++;
            }
            for (int i = right - 1; i >= left && top < bottom; i --) {
                a[bottom][i] = k ++;
            }
            for (int i = bottom - 1; i > top && left < right; i --) {
                a[i][left] = k ++;
            }
            left ++, right --, top ++, bottom --;
        }
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                cout << a[i][j] << " ";
            }
            cout << endl;
        }
        return 0;
    }
    
    • 1

    信息

    ID
    680
    时间
    1000ms
    内存
    128MiB
    难度
    8
    标签
    提交数
    54
    已通过
    10
    上传者