
本文共 3028 字,大约阅读时间需要 10 分钟。
BFS���������������������������������������������������������������������������������������������������������������������������������������������������A���������������B���������������������������������������������������������������������������������������������������������������������������������������������������������BFS������������������������������������������������������������������
���������������
������������������������������������3x2���������������������������������������������������A���B���*������������������������������������������������������������������������
���������������������������A���B���������������������*���������������������������������������������������
���������������������������������������������������������������������������������������������������������������
������������������������������������������������BFS������������������������������������������������������������������������������������������������������������
���������������
#include#include #include #include #include using namespace std;int dir[4] = { -1, 1, 4, -4 };// ������������������struct node { int x; string s;};void bfs() { queue q; set visited; // ������������ string initial = " *A**B \n **B\nA B"; // ������������������������������������������������������ node start; start.x = 0; start.s = " *A**B "; q.push(start); visited.insert(start.s); while (!q.empty()) { node current = q.front(); q.pop(); // ��������������������������� if (isTarget(current.s)) { cout << current.cnt << endl; return; } // ������������������ for (int i = 0; i < 4; ++i) { string newState = current.s; int x = current.x + dir[i]; if (isValidPosition(x)) { // ��������������������������� char temp = newState[x]; newState[x] = newState[x + 1]; newState[x + 1] = temp; node nextNode; nextNode.s = newState; nextNode.cnt = current.cnt + 1; if (visited.count(newState)) continue; visited.insert(newState); q.push(nextNode); } } } // ���������������������������������-1��� // ������������������������������������ } // ��������������������������������������� bool isTarget(const string& state) { return state.find("AB") != string::npos && state.find("BA") != string::npos; } int main() { // ��������������������� // ��������������� vector states; // ������������������������ for (int i = 0; i < test_case_count; ++i) { states.push_back(���������); } for (auto& state : states) { bfs(); } return 0; }
���������
���������������������������������������������������������������������������������
BFS������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������isTarget
������������A���B���������������
������������������������������������������������BFS���������������������������������������
发表评论
最新留言
关于作者
