find_shortest_sequences_from_to.cc 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "find_shortest_sequences_from_to.h"
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <queue>
  5. namespace {
  6. struct NumericSearchState {
  7. std::string sequence;
  8. int depth = 0;
  9. char state = 'A';
  10. };
  11. }
  12. std::vector<std::string> FindShortestSequencesFromTo(
  13. char from, char to,
  14. std::function<std::optional<char>(char, char)> apply_cmd) {
  15. std::vector<std::string> sequences;
  16. std::queue<NumericSearchState> states;
  17. states.emplace(NumericSearchState{
  18. .sequence = "",
  19. .depth = 0,
  20. .state = from,
  21. });
  22. int max_depth = 100;
  23. while (!states.empty()) {
  24. NumericSearchState state = std::move(states.front());
  25. states.pop();
  26. if (state.depth > max_depth) {
  27. continue;
  28. }
  29. if (state.state == to) {
  30. if (max_depth > state.sequence.size()) {
  31. max_depth = state.sequence.size();
  32. }
  33. state.sequence.push_back('A');
  34. sequences.emplace_back(std::move(state.sequence));
  35. continue;
  36. }
  37. for (auto c : {'<', '>', '^', 'v'}) {
  38. std::optional<char> maybe_next_state = apply_cmd(c, state.state);
  39. if (maybe_next_state) {
  40. NumericSearchState move_state = state;
  41. move_state.sequence.push_back(c);
  42. move_state.state = *maybe_next_state;
  43. ++move_state.depth;
  44. states.emplace(std::move(move_state));
  45. }
  46. }
  47. }
  48. std::vector<std::string> min_sequences;
  49. for (auto &s : sequences) {
  50. if (s.size() > max_depth + 1) {
  51. continue;
  52. }
  53. min_sequences.emplace_back(std::move(s));
  54. }
  55. return min_sequences;
  56. }