You are on page 1of 2

#include <bits/stdc++.

h>
using namespace std;

int transition(int variable_1, int variable_2)


{
switch(variable_1)
{
case 1: return variable_2^8; // state of man is changing
case 2: return variable_2^12; // state of man and goat is changing
case 3: return variable_2^10; // state of man and wolf is changing
case 4: return variable_2^9; // state of man and cabbage is changing
}
}

// Check whether the given state is valid state or not according to given
constraints
bool is_valid_state(int state)
{
switch(state)
{
case 6: // goat with wolf
case 5: // goat with cabbage
case 9: // man with cabbage only
case 10: // man with wolf only
case 8: //only man
case 7: // wolf with goat and cabbage
return 0;
default : return 1; // In all other case the state is valid
}
}

//checks whether the given state is present in the curent path


bool is_already_present(vector<int> current_path, int state)
{
auto it = find(current_path.begin(), current_path.end(), state);
if (it == current_path.end())
return 0;
else
return 1;
}

// Computes the paths


void find_path_Util(set<vector<int>> &output, int initial_state, int final_state,
vector<int> &current_path)
{
for (int i = 1; i <= 4; ++i)
{
int temp_var = transition(i, initial_state);
if (is_valid_state(temp_var))
{
if(is_already_present(current_path, temp_var))
continue;
current_path.push_back(temp_var);
if(temp_var == final_state)
output.insert(current_path);
else
find_path_Util(output, temp_var, final_state,
current_path);
current_path.pop_back(); // Backtracking
}
}
}

// Calls the utility function for the findpath


void find_path(set<vector<int>> &output)
{
vector<int> current_path = {};
int initial_state = 0, final_state = 15;
/*
Assuming bits representation as man,goat,wolf,cabbage
So value 6 (0110) shows goat and wolf are on destination.
and value 12 (1100) shows man and goat are on destination.
*/
find_path_Util(output, initial_state, final_state, current_path);
}

// Prints the solution


void print(set<vector<int>> output)
{
for(auto &i: output)
{
cout<<"Solution: START -> " << "____ -> " ;
for(auto &j : i)
cout<< (j & 8 ? "M":"_") << (j & 4 ? "G":"_") << (j & 2 ?
"W":"_") << (j & 1 ? "C":"_") <<" -> ";
cout<<"Reached"<<endl;
}
}

int main()
{
set<vector<int>> output;
find_path(output);
print(output);
return 0;
}

You might also like