8 Puzzle DFS
8 Puzzle DFS
package interview;
import java.util.*;
/**
*/
flag=false;
set=new HashSet<>();
fin=new int[][]{{1,2,3},{4,5,6},{7,8,0}};
int a=0,b=0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
puz[i][j]=scan.nextInt();
if(puz[i][j]==0){
a=i;b=j;
dfs(a,b,puz);
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(fin[i][j]!=puz[i][j]){
return false;
return true;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
s*=10;
s+=puz[i][j];
return s;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(puz[i][j]+" ");
System.out.println();
System.out.println();
System.out.println();
System.out.println("Answer:");
print(puz);
flag=true;
return;
int a=arrtoint(puz);
if(!set.contains(a)&&!flag){
set.add(a);
print(puz);
if(cx-1>=0&&puz[cx][cy]==0){
int temp=puz[cx][cy];
puz[cx][cy]=puz[cx-1][cy];
puz[cx-1][cy]=temp;
dfs(cx-1,cy,puz);
int temp2=puz[cx][cy];
puz[cx][cy]=puz[cx-1][cy];
puz[cx-1][cy]=temp2;
}
if(cx+1<3&&puz[cx][cy]==0){
int temp=puz[cx][cy];
puz[cx][cy]=puz[cx+1][cy];
puz[cx+1][cy]=temp;
dfs(cx+1,cy,puz);
int temp2=puz[cx][cy];
puz[cx][cy]=puz[cx+1][cy];
puz[cx+1][cy]=temp2;
if(cy-1>=0&&puz[cx][cy]==0){
int temp=puz[cx][cy];
puz[cx][cy]=puz[cx][cy-1];
puz[cx][cy-1]=temp;
dfs(cx,cy-1,puz);
int temp2=puz[cx][cy];
puz[cx][cy]=puz[cx][cy-1];
puz[cx][cy-1]=temp2;
if(cy+1<3&&puz[cx][cy]==0){
int temp=puz[cx][cy];
puz[cx][cy]=puz[cx][cy+1];
puz[cx][cy+1]=temp;
dfs(cx,cy+1,puz);
int temp2=puz[cx][cy];
puz[cx][cy]=puz[cx][cy+1];
puz[cx][cy+1]=temp2;
// set.remove(set.size()-1);
I/P:
1 0 3
4 2 5
7 8 6
O/P:
Answer:
123
456
780