yonezzzet
10/8/2017 - 3:17 PM

## 15puzzle-iddfs.cpp

``````#include <iostream>
#include <vector>
#include <stack>
#define N 4
#define N2 16
#define MAX_DEPTH 45
using namespace std;

class game{
public:
int b[N2];
int depth;
int last_move;
int empty_space;
};
game start;

bool complete(game &g){
for(int i=0;i<N2;i++){
if(g.b[i]!=i+1) return false;
}
return true;
}

bool dfs(int depth){
stack<game> s;
s.push(start);
while(!s.empty()){
game g = s.top(); s.pop();
if(g.depth==depth){
if(complete(g)) return g.depth;
continue;
}

int w=g.empty_space;
vector<int> move;
if(w%N>0  ) move.push_back(-1);
if(w%N<N-1) move.push_back(1);
if(w/N>0  ) move.push_back(-N);
if(w/N<N-1) move.push_back(N);

for(int i:move){
if(i==-g.last_move) continue;
game n=g;
swap(n.b[w],n.b[w+i]);
n.depth++;
n.last_move=i;
n.empty_space=w+i;
s.push(n);
}
}
return false;
}

int solve(){
for(int i=0;i<MAX_DEPTH;i++){
if(dfs(i)) return i;
}
return -1;
}

int main(){
for(int i=0;i<N2;i++){
int tmp; cin>>tmp;
if(tmp==0){
start.b[i]=N2;
start.empty_space=i;
}else{
start.b[i]=tmp;
}
}
start.depth=0;
start.last_move=0;

cout<<solve()<<endl;
}
``````