wennnnnnnn?

P1443 马的遍历

yuwenchong @ 2024-12-22 12:56:20

下面是代码

#include<iostream>

using namespace std;

int n, m;
int a[10086][10086];
bool bj[10086][10086] = {0};
int cs_h, cs_l;

void dfs(int h, int l, int cnt)
{
    if(h < 1 || h > n || l < 1 || l > m
    || bj[h][l] == 1)
    {
        return;
    }

    bj[h][l] = 1;
    a[h][l] = cnt;

    dfs(h + 2, l + 1, cnt + 1);
    dfs(h - 2, l + 1, cnt + 1);
    dfs(h + 2, l - 1, cnt + 1);
    dfs(h - 2, l - 1, cnt + 1);
    dfs(h + 1, l + 2, cnt + 1);
    dfs(h - 1, l + 2, cnt + 1);
    dfs(h + 1, l - 2, cnt + 1);
    dfs(h - 1, l - 2, cnt + 1);
}

int main()
{

    cin >> n >> m >> cs_h >> cs_l;

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            a[i][j] = -1;
        }
    }

    dfs(cs_h, cs_l, 0);

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            cout << a[i][j] << "    ";
        }
        cout << endl;
    }

    return 0;
}

问,最后空格数怎么调???


by Caiyuheng0923 @ 2024-12-22 12:59:57

printf("%-5d", a[i][j]);


by yuwenchong @ 2024-12-22 13:01:22

谢谢


by yuwenchong @ 2024-12-22 13:05:45

为什么还是只有最后一个点AC,其他都wa?


by Corange @ 2024-12-24 19:17:05

cout<<a[i][j]<<setw(4);

by Corange @ 2024-12-24 19:19:05

头文件用#include<bits/stdc++.h>


by Corange @ 2024-12-24 19:36:49

别用dfs,用bfs。


by Corange @ 2024-12-24 20:28:34

#include<bits/stdc++.h>
using namespace std;
struct point{
    int x=0,y=0;
    point(int a,int b){x=a,y=b;}
    point(){}
    point friend operator +(const point &a,const point &b){return point(a.x+b.x,a.y+b.y);}
};
const int maxn=405;
int S[maxn][maxn],n,m,x,y;
point mv[8]={point(-2,1),point(-1,2),point(1,2),point(2,1),
            point(2,-1),point(1,-2),point(-1,-2),point(-2,-1)};
void bfs(){
    int step=1;S[x][y]=0;
    queue<point> q;q.push(point(x,y));
    while(q.size()){
        int l=q.size();
        while(l--){
            point p=q.front();q.pop();
            for(int i=0;i<8;i++){
                point dp=p+mv[i];
                if(dp.x>0&&dp.x<=n&&dp.y>0&&dp.y<=m&&S[dp.x][dp.y]==-1){
                    q.push(dp);
                    S[dp.x][dp.y]=step;
                }
            }
        }
        ++step;
    }
    return;
}
int main(){
    ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
    cin>>n>>m>>x>>y;
    memset(S,0xff,sizeof(S));bfs();
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++) cout<<S[i][j]<<setw(4);
        cout<<'\n';
    }
    return 0;
}

|