20分,其他全RE,求调

P1746 离开中山路

zhaoyikuan @ 2024-08-29 14:18:07

#include <iostream>
#include <queue>
using namespace std;

int a[105][105], flag[105][105];
int di[4] = {-1, 0, 1, 0}, dj[4] = {0, 1, 0, -1};
int sx, sy, ex, ey, n;

void bfs() 
{
    queue<int> qi, qj;
    qi.push(sx);
    qj.push(sy);
    flag[sx][sy] = 0;
    while (!qi.empty()) 
    {
        int i = qi.front(); 
        int j = qj.front(); 
        for (int k = 0; k < 4; k++) 
        {
            int x = i + di[k];
            int y = j + dj[k];
            if (x >= 1 && x <= n && y >= 1 && y <= n && a[x][y] == 0 && flag[x][y] == -1)
{
            qi.push(x);
            qj.push(y);
            flag[x][y] = flag[i][j] + 1;
}
        }
        qi.pop();
        qj.pop();
    }
}
int main() 
{
    string v;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> v;
        for (int j = 1; j <= n; j++)
        {
            a[i][j] = v[j - 1] - '0';
        }
    }
    cin >> sx >> sy >> ex >> ey;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            flag[i][j] = -1;

    bfs();
    cout << flag[ex][ey] << endl;
    return 0;
}

by zhouzihang1 @ 2024-08-29 14:20:41

@zhaoyikuan 1 \le n \le 10^3


by known_error_ @ 2024-08-29 14:21:55

你数组倒是开大点啊!


by known_error_ @ 2024-08-29 14:22:51

#include <iostream>
#include <queue>
using namespace std;

int a[1005][1005], flag[1005][1005];
int di[4] = {-1, 0, 1, 0}, dj[4] = {0, 1, 0, -1};
int sx, sy, ex, ey, n;

void bfs() 
{
    queue<int> qi, qj;
    qi.push(sx);
    qj.push(sy);
    flag[sx][sy] = 0;
    while (!qi.empty()) 
    {
        int i = qi.front(); 
        int j = qj.front(); 
        for (int k = 0; k < 4; k++) 
        {
            int x = i + di[k];
            int y = j + dj[k];
            if (x >= 1 && x <= n && y >= 1 && y <= n && a[x][y] == 0 && flag[x][y] == -1)
{
            qi.push(x);
            qj.push(y);
            flag[x][y] = flag[i][j] + 1;
}
        }
        qi.pop();
        qj.pop();
    }
}
int main() 
{
    string v;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> v;
        for (int j = 1; j <= n; j++)
        {
            a[i][j] = v[j - 1] - '0';
        }
    }
    cin >> sx >> sy >> ex >> ey;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            flag[i][j] = -1;

    bfs();
    cout << flag[ex][ey] << endl;
    return 0;
}

by zhaoyikuan @ 2024-08-29 14:27:34

谢谢大佬!


|