【ACWing】845. 八数码

题目地址:

https://www.acwing.com/problem/content/847/

在一个 3 × 3 3\times 3 3×3的网格中,有 1 ∼ 8 1\sim 8 18 8 8 8个数字,以及一个字母 X X X。给定一个初始状态,每次可以将 X X X与其四周之一的数进行交换。问至少几步可以达到这样的排列:

1 2 3
4 5 6
7 8 x

如果不存在方案则返回 − 1 -1 1

输入格式:
输入占一行,将3×3的初始网格描绘出来。例如,如果初始网格如下所示:

1 2 3
x 4 6
7 5 8

则输入为:1 2 3 x 4 6 7 5 8

输出格式:
输出占一行,包含一个整数,表示最少交换次数。如果不存在解决方案,则输出 − 1 -1 1

思路是BFS。可以用字符串存储搜索的状态。代码如下:

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

int bfs(string& start) {
  string end = "12345678x";
  if (start == end) return 0;

  queue<string> q;
  unordered_map<string, int> dist;

  q.push(start);
  dist[start] = 0;

  static int d[] = {1, 0, -1, 0, 1};

  while (!q.empty()) {
    string cur = q.front(); q.pop();

    string tmp = cur;
    int k = cur.find('x');
    int x = k / 3, y = k % 3;
    for (int i = 0; i < 4; i++) {
      int nx = x + d[i], ny = y + d[i + 1];
      if (0 <= nx && nx < 3 && 0 <= ny && ny < 3) {
        int nk = nx * 3 + ny;
        swap(cur[k], cur[nk]);

        if (cur == end) return dist[tmp] + 1;

        if (!dist.count(cur)) {
          q.push(cur);
          dist[cur] = dist[tmp] + 1;
        }

        swap(cur[k], cur[nk]);
      }
    }
  }

  return -1;
}

int main() {
  string st;
  for (int i = 0; i < 9; i++) {
    char c;
    cin >> c;
    st += c;
  }

  cout << bfs(st) << endl;
}

时空复杂度 O ( V ) O(V) O(V) V V V为搜索的图的顶点个数。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值