当前位置: 首页 > article >正文

AB路线——BFS+分层图

题目

代码

#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
const int inf = 0x3f3f3f3f;
int g[N][N];
int dist[N][N][11];
int dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0};
int n, m, k;
void bfs()
{
  memset(dist, 0x3f, sizeof dist);
  dist[1][1][1] = 1;
  queue<array<int, 3>> q;
  q.push({1, 1, 1});

  while (q.size())
  {
    auto u = q.front();
    q.pop();
    int x = u[0], y = u[1], s = u[2];
    int d = dist[x][y][s];
    for (int i = 0; i < 4; i++)
    {
      int nx = x + dx[i], ny = y + dy[i], nc = d / k % 2, ns = (s + 1) % k;
      if (nx < 1 || ny < 1 || nx > n || ny > m || nc != g[nx][ny])
        continue;
      if (dist[nx][ny][ns] > d + 1)
      {
        dist[nx][ny][ns] = d + 1;
        q.push({nx, ny, ns});
      }
    }
  }
}
int main()
{
  ios::sync_with_stdio(0);
  cin.tie(0);

  cin >> n >> m >> k;
  for (int i = 1; i <= n; i++)
  {
    string s;
    cin >> s;
    for (int j = 0; j < m; j++)
    {
      g[i][j + 1] = (s[j] != 'A');
    }
  }

  bfs();

  int ans = inf;
  for (int i = 0; i < k; i++)
    ans = min(ans, dist[n][m][i]);

  if (ans == inf)
    ans = -1;
  else
    ans -= 1;
  cout << ans;
}


http://www.kler.cn/a/349119.html

相关文章:

  • Git---Git打标签
  • ui入门
  • Antsword-labs靶机渗透
  • Python基础语法条件
  • 基础IO -- 理解文件(1)
  • 使用tgz包下载安装clickhouse低版本
  • BERT--详解
  • 嵌入式Linux:信号掩码
  • 写一篇assignment的感悟
  • Python爬虫之正则表达式于xpath的使用教学及案例
  • Flutter资源管理(四)
  • LeetCode209.长度最小的子数组
  • 基于yolov8、yolov5的烟雾检测系统(含UI界面、训练好的模型、Python代码、数据集)
  • 【Vue】Vue2(7)
  • QT QML 练习4
  • 弘景光电:光学科技产品代表企业,创业板IPO即将上会
  • JavaScript object(2)
  • Java_EE(反射技术)
  • vue | 基础
  • 算法中并查集中的rank数组有什么用