The task is to convert a given state to the final state least possible steps. For example if you input a string like this:
213456
The state looks like this (it's always 6 characters):
2 1 3
4 5 6
The state you need to convert it to is always the same:
1 2 3
4 5 6
You need to switch the numbers to get the final state, you only switch them horizontally and vertically. It's not a hard task, but I'm having a problem with my never-ending recursion. Please don't comment on the code yet (using namespace std; not using functions for repeating processes etc.) since I'm not finished, I need you to help me understand why is this a never-ending recursion.
Edit: CODE IS NOW WORKING!
#include <iostream> #include <map> #include <string> #include <algorithm> #include <vector> using namespace std; int f(string s, map <string, int>& visited, int steps = 0) { string s2 = s; vector <int> solutions; solutions.push_back(721); if(s == "123456") return steps; else { swap(s2[0], s2[1]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } s2 = s; swap(s2[1], s2[2]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } s2 = s; swap(s2[3], s2[4]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } s2 = s; swap(s2[4], s2[5]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } s2 = s; swap(s2[0], s2[3]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } s2 = s; swap(s2[1], s2[4]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } s2 = s; swap(s2[2], s2[5]); if(visited.find(s2) == visited.end() or steps < visited[s2]) { visited[s2] = steps; solutions.push_back(f(s2, visited, steps + 1)); } return *(min_element(solutions.begin(), solutions.end())); } } int main() { string s; cin >> s; map <string, int> visited; cout << f(s, visited) << endl; return 0; } Sample input:
321456
Sample output:
3