2850. 将石头分散到网格图的最少移动次数
struct Node {
std::vector<int> current;
std::vector<int> remain;
};
class Solution {
public:
int minimumMoves(vector<vector<int>> &grid) {
int(grids_cost[])[9] = {
{0, 1, 2, 1, 2, 3, 2, 3, 4}, {1, 0, 1, 2, 1, 2, 3, 2, 3},
{2, 1, 0, 3, 2, 1, 4, 3, 2}, {1, 2, 3, 0, 1, 2, 1, 2, 3},
{2, 1, 2, 1, 0, 1, 2, 1, 2}, {3, 2, 1, 2, 1, 0, 3, 2, 1},
{2, 3, 4, 1, 2, 3, 0, 1, 2}, {3, 2, 3, 2, 1, 2, 1, 0, 1},
{4, 3, 2, 3, 2, 1, 2, 1, 0}};
int grid_linear_array[9];
std::vector<int> stones_gt_one;
std::vector<int> stones_eq_zero;
for (int line = 0; line < 3; line++) {
for (int column = 0; column < 3; column++) {
int stone_index = 3 * line + column;
grid_linear_array[stone_index] = grid[line][column];
if (grid_linear_array[stone_index] > 1) {
for (int i = 0; i < grid_linear_array[stone_index] - 1; i++) {
stones_gt_one.push_back(stone_index);
}
} else if (grid_linear_array[stone_index] == 0) {
stones_eq_zero.push_back(stone_index);
}
}
}
int cost_sum = -1;
std::queue<Node> q;
for (auto i : stones_eq_zero) {
struct Node node;
node.current.push_back(i);
for (auto j : stones_eq_zero) {
if (j != i) {
node.remain.push_back(j);
}
}
q.push(node);
}
while (!q.empty()) {
auto node = q.front();
q.pop();
if (node.remain.empty()) {
int cost = 0;
for (int zero_index = 0; zero_index < stones_eq_zero.size();
zero_index++) {
// std::cout << "(" << stones_gt_one[zero_index] << ", " <<
// node.current[zero_index] << "), ";
cost +=
grids_cost[stones_gt_one[zero_index]][node.current[zero_index]];
}
// std::cout << endl;
if (cost_sum == -1 || cost_sum > cost) {
cost_sum = cost;
}
continue;
}
for (auto i : node.remain) {
Node node_next;
node_next.current = node.current;
node_next.remain = node.remain;
node_next.current.push_back(i);
node_next.remain.erase(
std::remove(node_next.remain.begin(), node_next.remain.end(), i),
node_next.remain.end());
q.push(node_next);
}
}
return cost_sum;
}
};
python代码,用于枚举生成C++代码中的数组:
import numpy as np
a = np.array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
L = []
b = a.copy()
b += 2
for i in range(3):
b[:i, :] += 1
b[i:, :] -= 1
# print(b)
c = b.copy()
for j in range(3):
c[:, :j] += 1
c[:, j:] -= 1
# print(c)
L.append(list(c.ravel()))
print("{", end="")
for i in L:
print("{", end="")
for j in i:
print(j, end=" ,")
print("},")
print("};", end="")
P = []
for i in range(len(L)):
X = [[], [], [], [], []]
for j in range(len(L[i])):
X[L[i][j]].append(j)
P.append(X)
print("{", end="")
for i in P:
print("{", end="")
for j in i:
print("{", end="")
for k in j:
print(k, end=", ")
print("},")
print("},")
print("};", end="")