You are on page 1of 2

import java.util.

*;

class Node {
int[][] state;
Node parent;
int cost;

public Node(int[][] state) {


this.state = state;
this.parent = null;
this.cost = 0;
}
}

public class EightPuzzleSolver {


public static final int[][] GOAL_STATE = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 0} // 0 represents the blank space
};

public static void main(String[] args) {


int[][] initialState = generateRandomInitialState(); // Implement this
method to generate a random initial state
Node solution = ucs(initialState);
if (solution != null) {
printSolution(solution);
} else {
System.out.println("No solution found.");
}
}

public static Node ucs(int[][] initialState) {


Queue<Node> queue = new PriorityQueue<>(Comparator.comparingInt(node ->
node.cost));
Set<String> visited = new HashSet<>();

Node startNode = new Node(initialState);


queue.add(startNode);

while (!queue.isEmpty()) {
Node currentNode = queue.poll();
visited.add(Arrays.deepToString(currentNode.state));

if (Arrays.deepEquals(currentNode.state, GOAL_STATE)) {
return currentNode; // Found the solution
}

// Generate child nodes and add them to the queue


List<Node> children = generateChildren(currentNode);
for (Node child : children) {
if (!visited.contains(Arrays.deepToString(child.state))) {
queue.add(child);
}
}
}

return null; // No solution found


}
public static List<Node> generateChildren(Node parent) {
// Implement this method to generate child nodes by moving the blank space
in all possible directions
}

public static void printSolution(Node node) {


// Implement this method to print the solution path
}
}

You might also like