算法刷题记录:回行矩阵(未AC,TLE了)

题目链接:

https://ac.nowcoder.com/acm/contest/19306/1026

题目分析

这种题,画个图,模拟就对啦。

TLE代码

#include <iostream>

using namespace std;

int n, cnt;
int w[25][25];

int main()
{
    cin >> n;
    
    // 构建框架
    int dx = 1, dy = 1;
    while (1)
    {
        while (dy <= n) w[dx][dy ++ ] = ++ cnt;
        -- dy;
        while (dx <= n) w[ ++ dx][dy] = ++ cnt; 
        -- dx;
        while (dy >= 1) w[dx][ -- dy] = cnt ++ ;
        ++ dy, -- dx, -- cnt;
        while (w[dx][dy] == 0) w[dx -- ][dy] = cnt ++ ;
        break;
    }
    // cout << dx << ' ' << dy << ' ' << cnt << endl;
    ++ dx; ++ dy, -- cnt;
    while (1)
    {
        if (w[dx][dy] && w[dx - 1][dy] 
            && w[dx + 1][dy] && w[dx][dy - 1] 
            && w[dx][dy + 1]) break;
        // >
        while (!w[dx][dy]) w[dx][dy ++ ] = ++ cnt;
        // v
        -- dy;
        while (!w[ ++ dx][dy]) w[dx][dy] = ++ cnt;
        // <
        -- dx;
        while (!w[dx][ -- dy]) w[dx][dy] = ++ cnt;
        // ^
        ++ dy;
        while (!w[ -- dx][dy]) w[dx][dy] = ++ cnt;
        ++ dx, ++ dy;
    }
    
    for (int i = 1; i <= n; ++ i)
    {
        for (int j = 1; j <= n; ++ j)
            cout << w[i][j] << ' ';
        cout << endl;
    }
}
posted @ 2023-05-28 11:33  想个昵称好难ABCD  阅读(2)  评论(0编辑  收藏  举报