Search.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. #include <vector>
  2. #include <queue>
  3. #include <iostream>
  4. #include <unordered_map>
  5. #include <algorithm>
  6. #include <limits>
  7. struct GraphNode
  8. {
  9. // Adjacency list
  10. std::vector<GraphNode*> mAdjacent;
  11. };
  12. struct Graph
  13. {
  14. // A graph contains nodes
  15. std::vector<GraphNode*> mNodes;
  16. };
  17. struct WeightedEdge
  18. {
  19. // Which nodes are connected by this edge?
  20. struct WeightedGraphNode* mFrom;
  21. struct WeightedGraphNode* mTo;
  22. // Weight of this edge
  23. float mWeight;
  24. };
  25. struct WeightedGraphNode
  26. {
  27. std::vector<WeightedEdge*> mEdges;
  28. };
  29. struct WeightedGraph
  30. {
  31. std::vector<WeightedGraphNode*> mNodes;
  32. };
  33. struct GBFSScratch
  34. {
  35. const WeightedEdge* mParentEdge = nullptr;
  36. float mHeuristic = 0.0f;
  37. bool mInOpenSet = false;
  38. bool mInClosedSet = false;
  39. };
  40. using GBFSMap =
  41. std::unordered_map<const WeightedGraphNode*, GBFSScratch>;
  42. struct AStarScratch
  43. {
  44. const WeightedEdge* mParentEdge = nullptr;
  45. float mHeuristic = 0.0f;
  46. float mActualFromStart = 0.0f;
  47. bool mInOpenSet = false;
  48. bool mInClosedSet = false;
  49. };
  50. using AStarMap =
  51. std::unordered_map<const WeightedGraphNode*, AStarScratch>;
  52. float ComputeHeuristic(const WeightedGraphNode* a, const WeightedGraphNode* b)
  53. {
  54. return 0.0f;
  55. }
  56. bool AStar(const WeightedGraph& g, const WeightedGraphNode* start,
  57. const WeightedGraphNode* goal, AStarMap& outMap)
  58. {
  59. std::vector<const WeightedGraphNode*> openSet;
  60. // Set current node to start, and mark in closed set
  61. const WeightedGraphNode* current = start;
  62. outMap[current].mInClosedSet = true;
  63. do
  64. {
  65. // Add adjacent nodes to open set
  66. for (const WeightedEdge* edge : current->mEdges)
  67. {
  68. const WeightedGraphNode* neighbor = edge->mTo;
  69. // Get scratch data for this node
  70. AStarScratch& data = outMap[neighbor];
  71. // Only check nodes that aren't in the closed set
  72. if (!data.mInClosedSet)
  73. {
  74. if (!data.mInOpenSet)
  75. {
  76. // Not in the open set, so parent must be current
  77. data.mParentEdge = edge;
  78. data.mHeuristic = ComputeHeuristic(neighbor, goal);
  79. // Actual cost is the parent's plus cost of traversing edge
  80. data.mActualFromStart = outMap[current].mActualFromStart +
  81. edge->mWeight;
  82. data.mInOpenSet = true;
  83. openSet.emplace_back(neighbor);
  84. }
  85. else
  86. {
  87. // Compute what new actual cost is if current becomes parent
  88. float newG = outMap[current].mActualFromStart + edge->mWeight;
  89. if (newG < data.mActualFromStart)
  90. {
  91. // Current should adopt this node
  92. data.mParentEdge = edge;
  93. data.mActualFromStart = newG;
  94. }
  95. }
  96. }
  97. }
  98. // If open set is empty, all possible paths are exhausted
  99. if (openSet.empty())
  100. {
  101. break;
  102. }
  103. // Find lowest cost node in open set
  104. auto iter = std::min_element(openSet.begin(), openSet.end(),
  105. [&outMap](const WeightedGraphNode* a, const WeightedGraphNode* b) {
  106. // Calculate f(x) for nodes a/b
  107. float fOfA = outMap[a].mHeuristic + outMap[a].mActualFromStart;
  108. float fOfB = outMap[b].mHeuristic + outMap[b].mActualFromStart;
  109. return fOfA < fOfB;
  110. });
  111. // Set to current and move from open to closed
  112. current = *iter;
  113. openSet.erase(iter);
  114. outMap[current].mInOpenSet = true;
  115. outMap[current].mInClosedSet = true;
  116. } while (current != goal);
  117. // Did we find a path?
  118. return (current == goal) ? true : false;
  119. }
  120. bool GBFS(const WeightedGraph& g, const WeightedGraphNode* start,
  121. const WeightedGraphNode* goal, GBFSMap& outMap)
  122. {
  123. std::vector<const WeightedGraphNode*> openSet;
  124. // Set current node to start, and mark in closed set
  125. const WeightedGraphNode* current = start;
  126. outMap[current].mInClosedSet = true;
  127. do
  128. {
  129. // Add adjacent nodes to open set
  130. for (const WeightedEdge* edge : current->mEdges)
  131. {
  132. // Get scratch data for this node
  133. GBFSScratch& data = outMap[edge->mTo];
  134. // Add it only if it's not in the closed set
  135. if (!data.mInClosedSet)
  136. {
  137. // Set the adjacent node's parent edge
  138. data.mParentEdge = edge;
  139. if (!data.mInOpenSet)
  140. {
  141. // Compute the heuristic for this node, and add to open set
  142. data.mHeuristic = ComputeHeuristic(edge->mTo, goal);
  143. data.mInOpenSet = true;
  144. openSet.emplace_back(edge->mTo);
  145. }
  146. }
  147. }
  148. // If open set is empty, all possible paths are exhausted
  149. if (openSet.empty())
  150. {
  151. break;
  152. }
  153. // Find lowest cost node in open set
  154. auto iter = std::min_element(openSet.begin(), openSet.end(),
  155. [&outMap](const WeightedGraphNode* a, const WeightedGraphNode* b) {
  156. return outMap[a].mHeuristic < outMap[b].mHeuristic;
  157. });
  158. // Set to current and move from open to closed
  159. current = *iter;
  160. openSet.erase(iter);
  161. outMap[current].mInOpenSet = false;
  162. outMap[current].mInClosedSet = true;
  163. } while (current != goal);
  164. // Did we find a path?
  165. return (current == goal) ? true : false;
  166. }
  167. using NodeToParentMap =
  168. std::unordered_map<const GraphNode*, const GraphNode*>;
  169. bool BFS(const Graph& graph, const GraphNode* start, const GraphNode* goal, NodeToParentMap& outMap)
  170. {
  171. // Whether we found a path
  172. bool pathFound = false;
  173. // Nodes to consider
  174. std::queue<const GraphNode*> q;
  175. // Enqueue the first node
  176. q.emplace(start);
  177. while (!q.empty())
  178. {
  179. // Dequeue a node
  180. const GraphNode* current = q.front();
  181. q.pop();
  182. if (current == goal)
  183. {
  184. pathFound = true;
  185. break;
  186. }
  187. // Enqueue adjacent nodes that aren't already in the queue
  188. for (const GraphNode* node : current->mAdjacent)
  189. {
  190. // If the parent is null, it hasn't been enqueued
  191. // (except for the start node)
  192. const GraphNode* parent = outMap[node];
  193. if (parent == nullptr && node != start)
  194. {
  195. // Enqueue this node, setting its parent
  196. outMap[node] = current;
  197. q.emplace(node);
  198. }
  199. }
  200. }
  201. return pathFound;
  202. }
  203. void testBFS()
  204. {
  205. Graph g;
  206. for (int i = 0; i < 5; i++)
  207. {
  208. for (int j = 0; j < 5; j++)
  209. {
  210. GraphNode* node = new GraphNode;
  211. g.mNodes.emplace_back(node);
  212. }
  213. }
  214. for (int i = 0; i < 5; i++)
  215. {
  216. for (int j = 0; j < 5; j++)
  217. {
  218. GraphNode* node = g.mNodes[i * 5 + j];
  219. if (i > 0)
  220. {
  221. node->mAdjacent.emplace_back(g.mNodes[(i - 1) * 5 + j]);
  222. }
  223. if (i < 4)
  224. {
  225. node->mAdjacent.emplace_back(g.mNodes[(i + 1) * 5 + j]);
  226. }
  227. if (j > 0)
  228. {
  229. node->mAdjacent.emplace_back(g.mNodes[i * 5 + j - 1]);
  230. }
  231. if (j < 4)
  232. {
  233. node->mAdjacent.emplace_back(g.mNodes[i * 5 + j + 1]);
  234. }
  235. }
  236. }
  237. NodeToParentMap map;
  238. bool found = BFS(g, g.mNodes[0], g.mNodes[9], map);
  239. std::cout << found << '\n';
  240. }
  241. void testHeuristic(bool useAStar)
  242. {
  243. WeightedGraph g;
  244. for (int i = 0; i < 5; i++)
  245. {
  246. for (int j = 0; j < 5; j++)
  247. {
  248. WeightedGraphNode* node = new WeightedGraphNode;
  249. g.mNodes.emplace_back(node);
  250. }
  251. }
  252. for (int i = 0; i < 5; i++)
  253. {
  254. for (int j = 0; j < 5; j++)
  255. {
  256. WeightedGraphNode* node = g.mNodes[i * 5 + j];
  257. if (i > 0)
  258. {
  259. WeightedEdge* e = new WeightedEdge;
  260. e->mFrom = node;
  261. e->mTo = g.mNodes[(i - 1) * 5 + j];
  262. e->mWeight = 1.0f;
  263. node->mEdges.emplace_back(e);
  264. }
  265. if (i < 4)
  266. {
  267. WeightedEdge* e = new WeightedEdge;
  268. e->mFrom = node;
  269. e->mTo = g.mNodes[(i + 1) * 5 + j];
  270. e->mWeight = 1.0f;
  271. node->mEdges.emplace_back(e);
  272. }
  273. if (j > 0)
  274. {
  275. WeightedEdge* e = new WeightedEdge;
  276. e->mFrom = node;
  277. e->mTo = g.mNodes[i * 5 + j - 1];
  278. e->mWeight = 1.0f;
  279. node->mEdges.emplace_back(e);
  280. }
  281. if (j < 4)
  282. {
  283. WeightedEdge* e = new WeightedEdge;
  284. e->mFrom = node;
  285. e->mTo = g.mNodes[i * 5 + j + 1];
  286. e->mWeight = 1.0f;
  287. node->mEdges.emplace_back(e);
  288. }
  289. }
  290. }
  291. bool found = false;
  292. if (useAStar)
  293. {
  294. AStarMap map;
  295. found = AStar(g, g.mNodes[0], g.mNodes[9], map);
  296. }
  297. else
  298. {
  299. GBFSMap map;
  300. found = GBFS(g, g.mNodes[0], g.mNodes[9], map);
  301. }
  302. std::cout << found << '\n';
  303. }
  304. struct GameState
  305. {
  306. // (For tic-tac-toe, array of board)
  307. enum SquareState { Empty, X, O };
  308. SquareState mBoard[3][3];
  309. };
  310. struct GTNode
  311. {
  312. // Children nodes
  313. std::vector<GTNode*> mChildren;
  314. // State of game
  315. GameState mState;
  316. };
  317. void GenStates(GTNode* root, bool xPlayer)
  318. {
  319. for (int i = 0; i < 3; i++)
  320. {
  321. for (int j = 0; j < 3; j++)
  322. {
  323. if (root->mState.mBoard[i][j] == GameState::Empty)
  324. {
  325. GTNode* node = new GTNode;
  326. root->mChildren.emplace_back(node);
  327. node->mState = root->mState;
  328. node->mState.mBoard[i][j] = xPlayer ? GameState::X : GameState::O;
  329. GenStates(node, !xPlayer);
  330. }
  331. }
  332. }
  333. }
  334. float GetScore(const GameState& state)
  335. {
  336. // Are any of the rows the same?
  337. for (int i = 0; i < 3; i++)
  338. {
  339. bool same = true;
  340. GameState::SquareState v = state.mBoard[i][0];
  341. for (int j = 1; j < 3; j++)
  342. {
  343. if (state.mBoard[i][j] != v)
  344. {
  345. same = false;
  346. }
  347. }
  348. if (same)
  349. {
  350. if (v == GameState::X)
  351. {
  352. return 1.0f;
  353. }
  354. else
  355. {
  356. return -1.0f;
  357. }
  358. }
  359. }
  360. // Are any of the columns the same?
  361. for (int j = 0; j < 3; j++)
  362. {
  363. bool same = true;
  364. GameState::SquareState v = state.mBoard[0][j];
  365. for (int i = 1; i < 3; i++)
  366. {
  367. if (state.mBoard[i][j] != v)
  368. {
  369. same = false;
  370. }
  371. }
  372. if (same)
  373. {
  374. if (v == GameState::X)
  375. {
  376. return 1.0f;
  377. }
  378. else
  379. {
  380. return -1.0f;
  381. }
  382. }
  383. }
  384. // What about diagonals?
  385. if (((state.mBoard[0][0] == state.mBoard[1][1]) &&
  386. (state.mBoard[1][1] == state.mBoard[2][2])) ||
  387. ((state.mBoard[2][0] == state.mBoard[1][1]) &&
  388. (state.mBoard[1][1] == state.mBoard[0][2])))
  389. {
  390. if (state.mBoard[1][1] == GameState::X)
  391. {
  392. return 1.0f;
  393. }
  394. else
  395. {
  396. return -1.0f;
  397. }
  398. }
  399. // We tied
  400. return 0.0f;
  401. }
  402. float MinPlayer(const GTNode* node);
  403. float MaxPlayer(const GTNode* node)
  404. {
  405. // If this is a leaf, return score
  406. if (node->mChildren.empty())
  407. {
  408. return GetScore(node->mState);
  409. }
  410. float maxValue = -std::numeric_limits<float>::infinity();
  411. // Find the subtree with the maximum value
  412. for (const GTNode* child : node->mChildren)
  413. {
  414. maxValue = std::max(maxValue, MinPlayer(child));
  415. }
  416. return maxValue;
  417. }
  418. float MinPlayer(const GTNode* node)
  419. {
  420. // If this is a leaf, return score
  421. if (node->mChildren.empty())
  422. {
  423. return GetScore(node->mState);
  424. }
  425. float minValue = std::numeric_limits<float>::infinity();
  426. // Find the subtree with the minimum value
  427. for (const GTNode* child : node->mChildren)
  428. {
  429. minValue = std::min(minValue, MaxPlayer(child));
  430. }
  431. return minValue;
  432. }
  433. const GTNode* MinimaxDecide(const GTNode* root)
  434. {
  435. // Find the subtree with the maximum value, and save the choice
  436. const GTNode* choice = nullptr;
  437. float maxValue = -std::numeric_limits<float>::infinity();
  438. for (const GTNode* child : root->mChildren)
  439. {
  440. float v = MinPlayer(child);
  441. if (v > maxValue)
  442. {
  443. maxValue = v;
  444. choice = child;
  445. }
  446. }
  447. return choice;
  448. }
  449. float AlphaBetaMin(const GTNode* node, float alpha, float beta);
  450. float AlphaBetaMax(const GTNode* node, float alpha, float beta)
  451. {
  452. // If this is a leaf, return score
  453. if (node->mChildren.empty())
  454. {
  455. return GetScore(node->mState);
  456. }
  457. float maxValue = -std::numeric_limits<float>::infinity();
  458. // Find the subtree with the maximum value
  459. for (const GTNode* child : node->mChildren)
  460. {
  461. maxValue = std::max(maxValue, AlphaBetaMin(child, alpha, beta));
  462. if (maxValue >= beta)
  463. {
  464. return maxValue; // Beta prune
  465. }
  466. alpha = std::max(maxValue, alpha);
  467. }
  468. return maxValue;
  469. }
  470. float AlphaBetaMin(const GTNode* node, float alpha, float beta)
  471. {
  472. // If this is a leaf, return score
  473. if (node->mChildren.empty())
  474. {
  475. return GetScore(node->mState);
  476. }
  477. float minValue = std::numeric_limits<float>::infinity();
  478. // Find the subtree with the minimum value
  479. for (const GTNode* child : node->mChildren)
  480. {
  481. minValue = std::min(minValue, AlphaBetaMax(child, alpha, beta));
  482. if (minValue <= alpha)
  483. {
  484. return minValue; // Alpha prune
  485. }
  486. beta = std::min(minValue, beta);
  487. }
  488. return minValue;
  489. }
  490. const GTNode* AlphaBetaDecide(const GTNode* root)
  491. {
  492. // Find the subtree with the maximum value, and save the choice
  493. const GTNode* choice = nullptr;
  494. float maxValue = -std::numeric_limits<float>::infinity();
  495. float beta = std::numeric_limits<float>::infinity();
  496. for (const GTNode* child : root->mChildren)
  497. {
  498. float v = AlphaBetaMin(child, maxValue, beta);
  499. if (v > maxValue)
  500. {
  501. maxValue = v;
  502. choice = child;
  503. }
  504. }
  505. return choice;
  506. }
  507. void testTicTac()
  508. {
  509. GTNode* root = new GTNode;
  510. root->mState.mBoard[0][0] = GameState::O;
  511. root->mState.mBoard[0][1] = GameState::Empty;
  512. root->mState.mBoard[0][2] = GameState::X;
  513. root->mState.mBoard[1][0] = GameState::X;
  514. root->mState.mBoard[1][1] = GameState::O;
  515. root->mState.mBoard[1][2] = GameState::O;
  516. root->mState.mBoard[2][0] = GameState::X;
  517. root->mState.mBoard[2][1] = GameState::Empty;
  518. root->mState.mBoard[2][2] = GameState::Empty;
  519. GenStates(root, true);
  520. const GTNode* choice = AlphaBetaDecide(root);
  521. std::cout << choice->mChildren.size();
  522. }