ACM超时问题(Codeforces Round #442 (Div. 2)D. Olya and Energy Drinks)

  上次听学长说,关于标记数组最好换成布尔型的,节约空间时间,一直不以为然,直到做到Codeforces Round #442 (Div. 2)D. Olya and Energy Drinks的时候一直在44组测试数据超时,花了超长时间才发现是标记数组类型这里拉长了时间QAQ。这次一定记住了!!!(跟普通走迷宫的不同之处在于能走多步而已)

附上代码

#include <iostream>
#include <queue>
using namespace std;
const int maxn = 1e3 + 10;
char arr[maxn][maxn];
bool book[maxn][maxn];
int dx[] = { -1,0,1,0 }, dy[] = { 0,-1,0,1 };
int n, m, k;
int x1, y1, x2, y2;
struct node {
  int x, y;
  int step;
}temp;
queue<node>q;
int bfs() {
  if (x1 == x2 && y1 == y2) {
    return 0;
  }
  temp.x = x1;
  temp.y = y1;
  temp.step = 0;
  q.push(temp);
  book[x1][y1] = 1;
  while (!q.empty()) {
    temp = q.front();
    q.pop();
    int x = temp.x, y = temp.y, step = temp.step;
    for (int i = 0; i < 4; i++) {
      for (int j = 1; j <= k; j++) {
        int nx = x + dx[i] * j;
        int ny = y + dy[i] * j;
        if (nx == x2 && ny == y2) {
          return step + 1;
        }
        if (nx < 0 || nx >= n || ny < 0 || ny >= m || arr[nx][ny] == '#') {
          break;
        }
        if (book[nx][ny] == 0) {
          book[nx][ny] = 1;
          temp.x = nx;
          temp.y = ny;
          temp.step = step + 1;
          q.push(temp);
        }
      }
    }
  }
  return -1;
}
int main() {
  cin >> n >> m >> k;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      cin >> arr[i][j];
  cin >> x1 >> y1 >> x2 >> y2;
  x1--;
  y1--;
  x2--;
  y2--;
  cout << bfs() << endl;
  return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值