回文矩阵

#include 
using namespace std;
int n,m,k = 1,tol = 1;
int nums[20][20],dic[5][2] = {0,0,0,1,1,0,0,-1,-1,0};
int main()
{
    scanf("%d%d",&n,&m);
    nums[1][1] = 1;
    for(int i = 2,a = 1,b = 1;i <= n*m;i++){
        int x = a + dic[k][0];
        int y = b + dic[k][1];
        if(nums[x][y] == 0 && x <= n && x >= 1 && y <= m && y >= 1){
            nums[x][y] = ++tol;
            a = x;
            b = y;
        }
        else{
            if(++k == 5) k = 1;
            a += dic[k][0];
            b += dic[k][1];
            nums[a][b] = ++tol;
        }
    }
    for(int i = 1;i <= n;i ++){
        for(int j = 1;j <= m;j++){
            printf("%5d",nums[i][j]);
        }
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(回文矩阵)