70pts TLE三个点
  • 板块P1141 01迷宫
  • 楼主bus_man
  • 当前回复0
  • 已保存回复0
  • 发布时间2025/7/18 18:06
  • 上次更新2025/7/19 08:31:13
查看原帖
70pts TLE三个点
1632230
bus_man楼主2025/7/18 18:06

求调

#include <bits/stdc++.h>
#define maxn 1010
using namespace std;

const int walk[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

int n, m;
int M[maxn][maxn];
bool vis[maxn][maxn]; // 标记是否访问过
int ans[maxn][maxn];  // 记忆化

int change(char ch)
{
   if (ch == '0')
       return 0;
   return 1;
}

int main()
{
   ios::sync_with_stdio(false); // 加速读入
   cin.tie(0);

   cin >> n >> m;
   for (int i = 1; i <= n; i++)
   {
       for (int j = 1; j <= n; j++)
       {
           char ch;
           cin >> ch;
           // 映射
           M[i][j] = change(ch);
       }
   }
   for (int i = 1; i <= n; i++)
   {
       for (int j = 1; j <= n; j++)
       {
           ans[i][j] = 1;
       }
   }

   for (int I = 1; I <= m; I++)
   {
       for (int i = 1; i <= n; i++)
       {
           for (int j = 1; j <= n; j++)
           {
               vis[i][j] = 0;
           }
       }

       int x, y;
       cin >> x >> y;
       queue<pair<int, int>> q;
       q.push(make_pair(x, y));
       vis[x][y] = 1;

       // 如果之前搜过,直接输出答案
       if (ans[x][y] != 1)
       {
           cout << ans[x][y] << endl;
           continue;
       }

       // bfs
       while (!q.empty())
       {
           int nx = q.front().first, ny = q.front().second;
           q.pop();

           for (int i = 0; i < 4; i++)
           {
               int dx = nx + walk[i][0], dy = ny + walk[i][1];
               if (dx > n || dy > n || dx < 1 || dy < 1)
                   continue;
               if (M[nx][ny] == M[dx][dy] || vis[dx][dy])
                   continue;

               vis[dx][dy] = 1;
               q.push(make_pair(dx, dy));
               ans[x][y]++;
           }
       }

       cout << ans[x][y] << endl;
   }

   return 0;
}
2025/7/18 18:06
加载中...