- 添加了
printGrid
函数,用于输出当前的网格状态。 - 在
dfsIterative
函数中,在记录状态后调用printGrid
打印每次翻转后的状态。#include <iostream> #include <vector> #include <set> #include <stack> const int SIZE = 4; const int DIRECTIONS[5][2] = { {0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; // 翻转金币的函数,并输出当前网格状态 void flip(std::vector<std::vector<bool>>& grid, int x, int y) { for (int d = 0; d < 5; ++d) { int nx = x + DIRECTIONS[d][0]; int ny = y + DIRECTIONS[d][1]; if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE) { grid[nx][ny] = !grid[nx][ny]; } } } // 打印当前网格状态 void printGrid(const std::vector<std::vector<bool>>& grid) { for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { std::cout << (grid[i][j] ? '1' : '0') << " "; // 1 表示金币, 0 表示空位 } std::cout << std::endl; } std::cout << "-----------------" << std::endl; // 分隔行 } // 将当前网格状态转换为字符串 std::string gridToString(const std::vector<std::vector<bool>>& grid) { std::string result; for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < SIZE; ++j) { result += (grid[i][j] ? '1' : '0'); // 1 表示金币, 0 表示空位 } } return result; } // 迭代 DFS,记录状态 void dfsIterative(std::set<std::string>& uniqueStates) { std::stack<std::pair<std::vector<std::vector<bool>>, int>> stack; // 初始化网格:全是金币 std::vector<std::vector<bool>> initialGrid(SIZE, std::vector<bool>(SIZE, true)); stack.push({ initialGrid, 0 }); // 存储初始状态与下一个点击的位置 while (!stack.empty()) { auto current = stack.top(); // 访问当前网格和下一个位置 std::vector<std::vector<bool>>& currentGrid = current.first; int nextPos = current.second; stack.pop(); // 将当前状态转换为字符串并插入集合 uniqueStates.insert(gridToString(currentGrid)); // 打印当前网格状态 printGrid(currentGrid); // 遍历所有可能的点击位置 for (int i = nextPos; i < SIZE * SIZE; ++i) { int x = i / SIZE; int y = i % SIZE; // 点击 (x, y) 的金币 flip(currentGrid, x, y); stack.push({ currentGrid, i + 1 }); // 继续从下一个位置搜索 // 翻转回去以还原状态 flip(currentGrid, x, y); } } } int main() { // 集合用于存储唯一状态 std::set<std::string> uniqueStates; // 开始迭代 DFS dfsIterative(uniqueStates); // 输出结果 std::cout << "Total unique configurations: " << uniqueStates.size() << std::endl; return 0; }
输出结果:xxxx 4096
DFS-翻金币--总共可能性?
最新推荐文章于 2024-09-02 16:35:28 发布