Skip to content

Instantly share code, notes, and snippets.

@Mooophy
Created April 14, 2016 06:00
Show Gist options
  • Save Mooophy/d116c77c6633ada071ea8fbc8c472dde to your computer and use it in GitHub Desktop.
Save Mooophy/d116c77c6633ada071ea8fbc8c472dde to your computer and use it in GitHub Desktop.
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Node
{
public:
string state;
string path;
vector<Node> valid_children()
{
auto valid_children = vector<Node>{};
if (is_possible_up())
valid_children.push_back(up());
if (is_possible_right())
valid_children.push_back(right());
if (is_possible_down())
valid_children.push_back(down());
if (is_possible_left())
valid_children.push_back(left());
return valid_children;
}
private:
bool is_possible_up()
{
return state.find('0') > 2;
}
bool is_possible_right()
{
return (state.find('0') % 3) != 2;
}
bool is_possible_down()
{
return state.find('0') < 6;
}
bool is_possible_left()
{
return (state.find('0') % 3) != 0;
}
Node up()
{
Node child = Node{ child.path + 'U', child.state = state };
std::swap(child.state[state.find('0') - 3], child.state[state.find('0')]);
return child;
}
Node right()
{
Node child;
child.path = path;
child.path += 'R';
child.state = state;
std::swap(child.state[state.find('0') + 1], child.state[state.find('0')]);
return child;
}
Node down()
{
Node child;
child.path = path;
child.path += 'D';
child.state = state;
std::swap(child.state[state.find('0') + 3], child.state[state.find('0')]);
return child;
}
Node left()
{
Node child;
child.path = path;
child.path += 'L';
child.state = state;
std::swap(child.state[state.find('0') - 1], child.state[state.find('0')]);
return child;
}
};
int main() {
auto initNode = Node{ "041526783" , "" };
auto children = initNode.valid_children();
for (auto child : children)
{
cout << child.path << endl;
}
system("pause");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment