problemscpp
A collection of my answers to algorithm problems in c++.
| 函数
acwing::acwing845 命名空间参考

  1. 八数码
更多...

struct  hash
 

函数

int main (istream &cin, ostream &cout)
 
 TEST (acwing845, case1)
 
 TEST (acwing845, case2)
 

详细描述

  1. 八数码

函数说明

◆ main()

int acwing::acwing845::main ( istream &  cin,
ostream &  cout 
)

在文件 acwing.cpp7097 行定义.

7097 {
7098 array<array<char, 3>, 3> target{};
7099 array<array<char, 3>, 3> grid{};
7100 unordered_set<array<array<char, 3>, 3>, hash> us;
7101 int start_x;
7102 int start_y;
7103 for(int i = 0; i < 9; i++) {
7104 cin >> grid[i / 3][i % 3];
7105 if(grid[i / 3][i % 3] == 'x') {
7106 start_x = i / 3;
7107 start_y = i % 3;
7108 }
7109 target[i / 3][i % 3] = i + '1';
7110 }
7111 target[2][2] = 'x';
7112 queue<tuple<array<array<char, 3>, 3>, int, int, int>> q;
7113 q.push(make_tuple(grid, 0, start_x, start_y));
7114 us.insert(grid);
7115 while(!q.empty()) {
7116 auto [g, step, x, y] = q.front();
7117 q.pop();
7118 if(g == target) {
7119 cout << step;
7120 return 0;
7121 }
7122 pair<int, int> nexts[4] = {
7123 make_pair(x, y + 1),
7124 make_pair(x, y - 1),
7125 make_pair(x + 1, y),
7126 make_pair(x - 1, y)};
7127 for(auto &[nx, ny]: nexts) {
7128 if(nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {
7129 swap(g[nx][ny], g[x][y]);
7130 if(!us.contains(g)) {
7131 us.insert(g);
7132 q.push(make_tuple(g, step + 1, nx, ny));
7133 }
7134 swap(g[nx][ny], g[x][y]);
7135 }
7136 }
7137 }
7138 cout << -1;
7139 return 0;
7140 }

被这些函数引用 TEST().

◆ TEST() [1/2]

acwing::acwing845::TEST ( acwing845  ,
case1   
)

在文件 acwing_test.cpp3309 行定义.

3309 {
3310 istringstream in("2 3 4 1 5 x 7 6 8");
3311 auto out = ostringstream();
3312 main(in, out);
3313 const auto ans = out.str();
3314 ASSERT_EQ("19", ans);
3315 }
int main(int argc, char **argv)
Definition: main.cpp:5

引用了 main().

◆ TEST() [2/2]

acwing::acwing845::TEST ( acwing845  ,
case2   
)

在文件 acwing_test.cpp3317 行定义.

3317 {
3318 istringstream in("6 4 7 8 5 x 3 2 1");
3319 auto out = ostringstream();
3320 main(in, out);
3321 const auto ans = out.str();
3322 ASSERT_EQ("31", ans);
3323 }

引用了 main().