寒假每日一题day3 756. 蛇形矩阵(暴力模拟)我爱喝水,天天健康

756. 蛇形矩阵

题意;

就是形填矩阵。

思路:

模拟就可以了,根据四个方向(有不同种写法,但是本质是一样的)

AC(抽风大佬%%%,好像之前紫薯也介绍过这种写法,qwq)

# include <bits/stdc++.h>

using namespace std;
int g[110][110];
int main(){
    
    
    int n, m;
    cin>>n>>m;
    for(int x=1,y=1,i=1; i<=n*m;){
    
    
        while(!g[x][y]&&y<=m)g[x][y++]=i++;y--,x++;
        while(!g[x][y]&&x<=n) g[x++][y]=i++;x--;y--;
        while(!g[x][y]&&y>=1) g[x][y--]=i++;x--;y++;
        while(!g[x][y]&&x>=1) g[x--][y]=i++;x++;y++;
    }
    for(int i = 1; i <= n; i ++ ){
    
    
        for(int j = 1; j <= m; j ++ )cout<<g[i][j]<<' ';
        cout<<endl;
    }
    return 0;
}

AC(我的丑代码)

# include <bits/stdc++.h>
using namespace std;
const int N = 110;
int g[N][N];
int dx[]={
    
    0,1,0,-1};
int dy[]={
    
    1,0,-1,0};
int main(){
    
    
    int n, m;
    cin>>n>>m;
    for(int i = 0; i <= n+1; i ++ ) g[i][0] = g[i][m+1] = -1;
    for(int i = 0; i <= m+1; i ++ ) g[0][i] = g[n+1][i] = -1;
    int cnt = 0, x = 1, y =0,  p =0;
    while(1){
    
    
        bool ok = false;
        for(int i = 0; i < 4&&!ok; i ++ , p =(p+1)%4){
    
    
            int tx = x+dx[p];
            int ty = y +dy[p];
            if(!g[tx][ty]){
    
    
                x = tx;
                y= ty;
                g[x][y] = ++cnt;
                ok = true;
                break;
            }
        }
        if(!ok)break;
    }
    for(int i = 1; i <= n; i ++ ){
    
    
        for(int j = 1; j <= m; j ++ ){
    
    
            cout<<g[i][j]<<' ';
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45377553/article/details/112483932
今日推荐