蛇形矩阵

题目描述

给出一个不大于 9 的正整数 nn,输出 n×n 的蛇形方阵。

从右上角上角填上 1 开始,顺时针方向依次填入数字

 

样例输入:

4

样例输出:

10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4

 

第一思路就是搜索,从右上角即1开始搜起,碰到边界就转向。方向用direction%4判断上下左右

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>

#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline

using namespace std;
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;

In ll read()
{
    ll ans = 0;
    char ch = getchar() , las = ' ';
    while(!isdigit(ch)) 
        las = ch, ch = getchar();
    while(isdigit(ch)) 
        ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
    if(las == '-') 
        ans = -ans;
    return ans;
}

In void write(ll x)
{
    if(x < 0) 
        x = -x, putchar('-');
    if(x >= 10) 
        write(x / 10);
    putchar(x % 10 + '0');
}

int a[10001][10001];
int n , direction , c = 1;

void dfs(int x,int y)
{
    if(x < 1 || y < 1 || x > n || y > n)
    {
        direction++;
        return;
    }
    if(a[x][y] != 0)
    {
        direction++;
        return;
    }
    a[x][y] = c;
    c++;
    while(c <= n * n)
    {
        if(direction % 4 == 0) 
            dfs(x + 1 , y);
        else 
            if(direction % 4 == 1) 
                dfs(x , y - 1);
        else 
            if(direction % 4 == 2) 
                dfs(x - 1 , y);
        else 
            dfs(x , y + 1);
    }
}
int main()
{
    n = read();
    dfs(1 , n);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
            write(a[i][j]) , space;
        enter;
    }
    return 0;
}

 

posted @ 2020-10-21 22:31  Tenderfoot  阅读(188)  评论(0编辑  收藏  举报