The depth first search does not function properly. Honestly I am not sure if this is the current way of implementation. I am new to implementing graph and want to be a pro at it.
Where am I going wrong and I do not understand how do I print the elements either in the dfs() function so I can know how dfs should be like.
Would getter & setter method for child elements is recommended?
Here is my code:
package graphs;
public enum State {
Unvisited,Visiting,Visited;
}
package graphs;
public class Node {
public Node[] adjacent;
public int adjacentCount;
private String vertex;
public graphs.State state;
public Node(String vertex)
{
this.vertex = vertex;
}
public Node(String vertex, int adjacentlen)
{
this.vertex = vertex;
adjacentCount = 0;
adjacent = new Node[adjacentlen];
}
public void addAdjacent(Node adj)
{
if(adjacentCount < 30)
{
this.adjacent[adjacentCount] = adj;
adjacentCount++;
}
}
public Node[] getAdjacent()
{
return adjacent;
}
public String getVertex()
{
return vertex;
}
}
public class Graph {
public int count; // num of vertices
private Node vertices[];
public Graph()
{
vertices = new Node[8];
count = 0;
}
public void addNode(Node n)
{
if(count < 10)
{
vertices[count] = n;
count++;
}
else
{
System.out.println("graph full");
}
}
public Node[] getNode()
{
return vertices;
}
}
package graphs;
import java.util.Stack;
import graphs.State;
public class Dfs {
/**
* #param args
*/
static boolean visited[];
public void dfs(Node root)
{
if(root == null) return;
Stack<Node> s = new Stack<Node>();
s.push(root);
root.state = State.Visited;
System.out.println("root:"+root.getVertex() + "\t");
while(!s.isEmpty())
{
Node u = s.pop();
for(Node n: u.getAdjacent())
{
if(n.state != State.Visited)
{
dfs(n);
}
}
}
}
public static Graph createNewGraph()
{
Graph g = new Graph();
Node[] temp = new Node[8];
temp[0] = new Node("A", 3);
temp[1] = new Node("B", 3);
temp[2] = new Node("C", 1);
temp[3] = new Node("D", 1);
temp[4] = new Node("E", 1);
temp[5] = new Node("F", 1);
temp[0].addAdjacent(temp[1]);
temp[0].addAdjacent(temp[2]);
temp[0].addAdjacent(temp[3]);
temp[1].addAdjacent(temp[0]);
temp[1].addAdjacent(temp[4]);
temp[1].addAdjacent(temp[5]);
temp[2].addAdjacent(temp[0]);
temp[3].addAdjacent(temp[0]);
temp[4].addAdjacent(temp[1]);
temp[5].addAdjacent(temp[1]);
for (int i = 0; i < 7; i++)
{
g.addNode(temp[i]);
}
return g;
}
public static void main(String[] args) {
Graph g = createNewGraph();
Dfs s = new Dfs();
//Node[] n = g.getNode();
s.dfs(g.getNode()[0]);
}
}
You don't need stack here. Only recursion:
public void dfs(Node node) {
if (node == null) {
return;
}
System.out.println("Node: " + node.getVertex());
node.state = State.Visited;
for (Node n : node.getAdjacent()) {
if (n.state != State.Visited) {
dfs(n);
}
}
}
UPDATE
To check path existence:
public boolean isPath(Graph graph, Node start, Node target) {
for (Node node : graph.getNode()) {
if (node != null) {
node.state = State.Unvisited;
}
}
dfs(start);
return target.state == State.Visited;
}
Related
Can someone help me with the interval search in binary tree.
I understand how to check left side of the tree,but I have troubles with chicking right side of it.
This is my code by now.
private boolean search(BSTNode r, int from,int till){
boolean found = false;
int arr[];
arr=new int[10];
int i=0;
while (r != null)
{
int rval = r.getData();
if (from < rval && till >rval) {
r = r.getLeft();
arr[i]=rval;
i++;
}else
r=r.getRight();
}
return found;
}
This is full class of BSTNode.
From and till it is range of interval(from
class BSTNode
{
BSTNode left, right;
int data;
/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BSTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BSTNode n)
{
right = n;
}
/* Function to get left node */
public BSTNode getLeft()
{
return left;
}
/* Function to get right node */
public BSTNode getRight()
{
return right;
}
You can search by using queue like this:
public boolean search(Integer from, Integer till) {
return search(root, from, till);
}
private boolean search(BSTNode root, Integer from, Integer till) {
boolean found = false;
Queue<BSTNode> queue = new ArrayDeque<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
BSTNode node = queue.poll();
int data = node.getData();
if (from < data && till > data) {
found = true;
list.add(data);
}
if (node.getLeft() != null)
queue.add(node.getLeft());
if (node.getRight() != null)
queue.add(node.getRight());
}
System.out.println(list);
return found;
}
, full code
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
// Tree building...
tree.insert(50);
tree.insert(40);
tree.insert(20);
tree.insert(10);
tree.insert(50);
System.out.println(tree.search(10, 30));
}
static class BinarySearchTree {
private BSTNode root;
public void insert(Integer item) {
root = insert(root, item);
}
private BSTNode insert(BSTNode node, Integer item) {
if (node == null) {
return new BSTNode(item);
} else if (item.compareTo(node.data) == 0) {
return node;
} else if (item.compareTo(node.data) < 0) {
node.setRight(insert(node.r, item));
return node;
} else {
node.setLeft(insert(node.l, item));
return node;
}
}
public Integer find(Integer target) {
return find(root, target);
}
private Integer find(BSTNode node, Integer target) {
if (node == null) {
return null;
}
Integer cmd = target.compareTo(node.data);
if (cmd == 0) {
return node.data;
} else if (cmd < 0) {
return find(node.getRight(), target);
} else {
return find(node.getLeft(), target);
}
}
public boolean search(Integer from, Integer till) {
return search(root, from, till);
}
private boolean search(BSTNode root, Integer from, Integer till) {
boolean found = false;
Queue<BSTNode> queue = new ArrayDeque<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
BSTNode node = queue.poll();
int data = node.getData();
if (from < data && till > data) {
found = true;
list.add(data);
}
if (node.getLeft() != null)
queue.add(node.getLeft());
if (node.getRight() != null)
queue.add(node.getRight());
}
System.out.println(list);
return found;
}
}
static class BSTNode {
Integer data;
BSTNode l = null;
BSTNode r = null;
public BSTNode(Integer data) {
super();
this.data = data;
}
public Integer getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BSTNode getLeft() {
return l;
}
public void setLeft(BSTNode l) {
this.l = l;
}
public BSTNode getRight() {
return r;
}
public void setRight(BSTNode r) {
this.r = r;
}
#Override
public String toString() {
return "BSTNode [data=" + data + ", l=" + l + ", r=" + r + "]";
}
}
, the output
[20]
true
I have a binary tree program that sorts smaller/equal numbers to the left of the parent, and larger numbers to the right of the parent, and I want to print out a diagram of it, but I don't know how to print it so it formats well. Also, should the print method be part of the TreeDriver class, or part of the TreeNode class to recursively access every node.
Here are the classes:
TreeDriver:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* This class serves as the driver for a generic TreeNode, giving it the type of Integer.
*/
public class TreeDriver
{
//region Instance Variables
TreeNode<Integer> root;
//endregion
//region Constructors
public TreeDriver() throws FileNotFoundException
{
fill();
System.out.println("Count: " + root.getCount());
}
//endregion
//region Public Methods
public void fill() throws FileNotFoundException
{
Scanner reader = new Scanner(new File("TreeValueSource"));
String temp;
Integer entry;
makeRoot();
while (reader.hasNext())
{
temp = reader.nextLine();
if (temp.contains("//"))
{
if (reader.hasNext())
temp = reader.nextLine();
else break;
}
else if (checkInt(temp))
{
entry = new Integer(temp);
root.add(entry);
}
else System.out.println("ERROR IN FILL");
}
}
private void makeRoot()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a root value(default 50): ");
String input = scan.next();
if (checkInt(input))
root = new TreeNode<>(new Integer(input));
else
root = new TreeNode<>(50);
}
public void printCount()
{
System.out.println(root.getCount());
}
//endregion
//region Private Methods
private boolean checkInt(String candidate)
{
boolean parsable = true;
try
{
Integer.parseInt(candidate);
} catch (NumberFormatException e)
{
parsable = false;
}
return parsable;
}
//endregion
}
TreeNode:
public class TreeNode<T extends Comparable<T>>
{
//region Instance Variables
//Links
private TreeNode<T> leftChild; //Left Link
private TreeNode<T> rightChild; //Right Link
//Properties
private T data; //Info Stored by the TreeNode
private int childCount; //Number of Children
private int depth; //Level of the Node in the Tree
//endregion
//region Constructors
public TreeNode(T data, int parentDepth)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = parentDepth + 1;
this.data = data;
}
public TreeNode(T data)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = 0;
this.data = data;
System.out.println("A Root was Created");
}
//endregion
//region Public Methods
/**
* ADD
* Adds a new TreeNode to the tree. Left if equal or smaller, Right if larger
*
* #param data The data held by the TreeNode
* #see TreeNode
*/
public void add(T data)
{
if (this.data.compareTo(data) <= 0)
{
addLeft(data);
} else if (this.data.compareTo(data) > 0)
{
addRight(data);
} else
{
System.out.println("ERROR IN TREENODE.ADD");
}
}
public int getCount()
{
return count();
}
/**
* IS LEAF
* Determines if the current node has no children
*
* #return True if no children, False otherwise
*/
public boolean isLeaf()
{
return childCount == 0;
}
//endregion
//region Private Methods
//Adds the data to the left of this.TreeNode
private void addLeft(T data)
{
if (null == leftChild)
{
leftChild = new TreeNode(data, depth);
childCount += 1;
} else
leftChild.add(data);
}
//Adds the data to the right of this.TreeNode
private void addRight(T data)
{
if (null == rightChild)
{
rightChild = new TreeNode(data, depth);
childCount += 1;
} else
rightChild.add(data);
}
/**
* COUNT
* Recursively counts the number of TreeNodes
*
* #return the number of TreeNodes, 0 if an error
*/
private int count()
{
if (isLeaf())
{
return 1;
} else if (childCount == 2)
{
return 1 + leftChild.count() + rightChild.count();
} else if (null == leftChild)
{
return 1 + rightChild.count();
} else if (null == rightChild)
{
return 1 + leftChild.count();
} else
{
System.out.println("ERROR IN COUNT AT DEPTH " + depth);
return 0;
}
}
//endregion
}
You can use this answer as a model
[How to print binary tree diagram?
Modifying the BtreePrinter Class. And no you shouldn't put the print method in the TreeDriver class.
class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
I am having trouble with my swap method in the Quick Sort program. I'm implementing it from a QuickSort method that sorts arrays. Here I take in a file with an integer on each line, it puts the number in a doubly linked list and then sorts the list and outputs to a new file. I need help with the swap method and what else I need to add or do to make it work properly. Any advise would help and examples are best. Thank you
//swap A[pos1] and A[pos2]
public static void swap(DList A, int pos1, int pos2){
int temp = A.get(pos1);
A[pos1] = A[pos2];
A[pos2] = temp;
}
My entire program for quicksort looks like this:
import java.util.*;
import java.io.*;
public class Test_QuickSort{
private static Scanner input = new Scanner(System.in);
private static DList list = new DList();
public static void main(String[] args) throws FileNotFoundException
{
input = new Scanner(new File("data.txt"));
while (input.hasNext())
{
String s = input.nextLine();
DNode g = new DNode(Integer.parseInt(s));
list.addLast(g);
}
//int[] A = {1,4,6,2};
QuickSort(list, 0, list.size()-1);
//for(int i = 0; i < A.length; i++)
// System.out.print(A[i] + " ");
}
public static void QuickSort(DList A, int left, int right){
if(left >= right)
return;
int pivot_index = partition(A, left, right);
QuickSort(A, left, pivot_index - 1);
QuickSort(A, pivot_index + 1, right);
}
public static int partition(DList A, int left, int right){
int pivot = A.get(right);
int index = left;
for(int i = left; i < right; i++){
if(A.get(i) <= pivot){
swap(A, index, i);
index ++;
}
}
swap(A, index, right);
return index;
}
//swap A[pos1] and A[pos2]
public static void swap(DList A, int pos1, int pos2){
int temp = A.get(pos1);
A[pos1] = A[pos2];
A[pos2] = temp;
}
}
My DList Method looks like this:
class DNode {
protected int element; // String element stored by a node
protected DNode next, prev; // Pointers to next and previous nodes
public DNode(int e)
{
element = e;
prev = null;
next = null;
}
public DNode()
{
element = 0;
next = null;
prev = null;
}
public DNode(int e, DNode p, DNode n) {
element = e;
prev = p;
next = n;
}
public int getElement() {
return element; }
public DNode getPrev() {
return prev; }
public DNode getNext() {
return next; }
public void setElement(int newElem) { element = newElem; }
public void setPrev(DNode newPrev) { prev = newPrev; }
public void setNext(DNode newNext) { next = newNext; }
}
public class DList {
protected int size;
protected DNode header, trailer;
public DList() {
size = 0;
header = new DNode(0, null, null);
trailer = new DNode(0, header, null);
header.setNext(trailer);
}
public int size() {
return size; }
public boolean isEmpty() {
return (size == 0); }
public DNode getFirst() throws IllegalStateException {
if (isEmpty()) throw new IllegalStateException("List is empty");
return header.getNext();
}
public DNode getLast() throws IllegalStateException {
if (isEmpty()) throw new IllegalStateException("List is empty");
return trailer.getPrev();
}
public DNode getPrev(DNode v) throws IllegalArgumentException {
if (v == header) throw new IllegalArgumentException
("Cannot move back past the header of the list");
return v.getPrev();
}
public int get(int pos)
{
DNode current = new DNode();
for(int i = 0; i <= pos && current != null; i++)
{
if(pos == 0){
current = header;
}
else{
current = current.next;
break;
}
}
return current.element;
}
public DNode getNext(DNode v) throws IllegalArgumentException {
if (v == trailer) throw new IllegalArgumentException
("Cannot move forward past the trailer of the list");
return v.getNext();
}
public void addBefore(DNode v, DNode z) throws IllegalArgumentException {
DNode u = getPrev(v); // may throw an IllegalArgumentException
z.setPrev(u);
z.setNext(v);
v.setPrev(z);
u.setNext(z);
size++;
}
public void addAfter(DNode v, DNode z) {
DNode w = getNext(v); // may throw an IllegalArgumentException
z.setPrev(v);
z.setNext(w);
w.setPrev(z);
v.setNext(z);
size++;
}
public void addFirst(DNode v) {
addAfter(header, v);
}
public void addLast(DNode v) {
addBefore(trailer, v);
}
public boolean hasPrev(DNode v) {
return v != header; }
public boolean hasNext(DNode v) {
return v != trailer; }
public String toString() {
String s = "[";
DNode v = header.getNext();
while (v != trailer) {
s += v.getElement();
v = v.getNext();
if (v != trailer)
s += ",";
}
s += "]";
return s;
}
}
The reason you are always retrieving the same element in DList.get is that you stop looping after the first iteration. Simply remove the break-statement, and the loop should work as intended.
public int get(int pos)
{
DNode current = new DNode();
for(int i = 0; i <= pos && current != null; i++)
{
if(pos == 0){
current = header;
}
else{
current = current.next;
// break; <-- remove this
}
}
return current.element;
}
Side note: You could get rid of the if-statement, if you would initialize current to header:
public int get(int pos)
{
DNode current = header;
for(int i = 1; i <= pos && current != null; i++)
{
current = current.next;
}
return current.element;
}
Now regarding your swap-method: As already stated, you try to treat the instance of DList as an array by trying to dereference an element using square-brackets. Instead, you should implement a method in DList that allows setting an element at a certain position. For example:
public void setAt(int pos, int value){
DNode current = header;
for(int i = 1; i <= pos && current != null; i++){
current = current.next;
}
if(current != null)
current.setElement(value);
else
throw new IndexOutOfBoundsException();
}
Now you can change your swap-method to:
public static void swap(DList a, int pos1, int pos2){
int temp = a.get(pos1);
a.setAt(pos1, a.get(pos2));
a.setAt(pos2, temp);
}
I am dealing with the following problem.
I have created a circular list, and i am also able to create x number of nodes for the number of people required in the circle. I am however stuck as i do not know how exactly i will iterate through the list for every nth person(node). I think i will need to create my own iterator but not sure how to go about it. I know it might be possible to import one from library but i don't want to do that as that will kill the learning process for me.
Here is the code for my Node Class
public class Node {
public int iData;
public Node next;
public Node(int x) {
iData = x;
}
public void displayNode() {
System.out.print(iData + " ");
}
}
Here is the code for Circular Linked List
public class CircularList {
private Node first;
private Node last;
private Node current;
private int count; // total items in the list
public CircularList getCurrent;
public CircularList() {
first = null;
last = null;
current = null;
count = 0;
}
public boolean isEmpty() {
return first == null;
}
public void step() {
current = current.next;
}
public Node getCurrent() {
return current;
}
public void insert(int x) {
Node newNode = new Node(x);
if (isEmpty()) {
first = newNode;
current = first;
} else {
current.next = newNode;
}
newNode.next = first;
last = newNode;
step();
count++;
}
public boolean search(int x) {
Node search = first;
int y = 0;
while (search.iData != x && y < count) {
search = search.next;
y++;
}
if (search.iData == x) {
System.out.println("Found the value: " + search.iData);
return true;
} else {
System.out.println("Value not found in list");
return false;
}
}
public void delete(int x) {
Node prev = first;
Node curr = first.next;
int y = 0;
while (y < count && curr.iData != x) {
prev = curr;
curr = curr.next;
}
if (count == 1) {
first = null;
count--;
} else {
prev.next = curr.next;
count--;
}
}
public void displayList() {
int x = 0;
Node printer = first;
while (x < count) {
printer.displayNode();
printer = printer.next;
x++;
}
}
}
Here is the code for my Josephus Class
public class Josephus {
private int numOfPeople; // number of people in a circle
private int countNum; // number used for counting off
CircularList circle;
public Josephus() {
circle = new CircularList();
numOfPeople = 0;
countNum = 0;
}
public void setNumOfPeople(int x) {
numOfPeople = x;
}
public int getNumOfPeople() {
return numOfPeople;
}
public void setCountNum(int x) {
countNum = x;
}
public int getcountNum() {
return countNum;
}
public void addPeople(int x) {
for (int i = 1; i < x; i++) {
circle.insert(i);
}
}
public void display() {
circle.displayList();
}
}
I need guidance in the right direction as to what i should do now. I do not ask for code or the answer. i want someone to push me towards the solutions. I can't go to sleep unless i solve this tonight.
First of all there is a lot of code because i really don't know where my issue is, I do apologise!
I'm making a program that solves a varying size puzzle for eg (3x3 with 0-8) The zero represents a blank tile the objective is to move the the blank tile around until the goal state is reached. At the moment I am using Depth First Search to solve the puzzle. Netbeans returns a 'OutOfMemory' error when i run the program however if I change the goal state so it only requires one move to complete it displays the solution. Below is my code, I've only added some of the classes because I don't want this post being ridiculously long. Please let me know if you require the other classes
EDIT: Inserted wrong code for board class
Depth First Search Class
package npuzzle;
import java.util.ArrayList;
import java.util.Stack;
public class DFSearch {
public static void search(int[][] initial, int[][] goal, int rows, int columns)
{
Board board = new Board(initial, goal, rows, columns, "");
Node root = new Node(board);
Stack<Node> stack = new Stack<Node>();
stack.add(root);
performSearch(stack, board);
}
public static void performSearch(Stack<Node> s, Board board)
{
int searchCount = 1;
while (!s.isEmpty())
{
Node tNode = (Node) s.pop();
//if not goal state
if (!tNode.getCurrentState().isGoalState())
{
ArrayList<State> tChildren = tNode.getCurrentState().gChildren();
for (int i = 0; i < tChildren.size(); i++)
{
Node newNode = new Node(tNode, tChildren.get(i), tNode.getGCost() + tChildren.get(i).findCost(), 0);
if(!isRepeatedState(newNode))
{
s.add(newNode);
}
}
searchCount++;
}
else
{
tNode.getCurrentState().printState();
System.exit(0);
//PRINTING OF DIRECTIONS
}
}
System.out.println("Error! No solution found!");
}
private static boolean isRepeatedState(Node c)
{
boolean returnVal = false;
Node checkNode = c;
while(c.getParent() != null && !returnVal)
{
if (c.getParent().getCurrentState().equals(checkNode.getCurrentState()))
{
returnVal = true;
}
c = c.getParent();
}
return returnVal;
}
}
Board Class
package npuzzle;
import java.util.ArrayList;
import java.util.Arrays;
public class Board implements State
{
private int PUZZLE_SIZE = 0;
private int outOfPlace = 0;
private int rows;
private int columns;
private int[][] GOAL;
private int[][] currentBoard;
private String directions = "";
public Board(int[][] initial, int[][] goal, int N, int M, String direction)
{
currentBoard = initial;
GOAL = goal;
rows = N;
columns = M;
PUZZLE_SIZE = rows*columns;
directions = direction;
setOutOfPlace();
}
#Override
public boolean isGoalState() {
if (Arrays.deepEquals(currentBoard, GOAL))
{
return true;
}
return false;
}
#Override
public ArrayList<State> gChildren() {
ArrayList<State> children = new ArrayList<State>();
int[] blanktile = getBlankTile();
int[] newblanktile = Arrays.copyOf(blanktile, blanktile.length);
if (blanktile[0] != 0) {
newblanktile[0]--;
Swap(newblanktile, blanktile, children, "up");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
if (blanktile[1] != 0) {
newblanktile[1]--;
Swap(newblanktile, blanktile, children, "left");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
if (blanktile[0] != (this.rows - 1)) {
newblanktile[0]++;
Swap(newblanktile, blanktile, children, "down");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
if (blanktile[1] != (this.columns - 1)) {
newblanktile[1]++;
Swap(newblanktile, blanktile, children, "right");
newblanktile = Arrays.copyOf(blanktile, blanktile.length);
}
return children;
}
#Override
public double findCost() {
return 1;
}
#Override
public void printState() {
System.out.println(directions);
}
#Override
public boolean equals(State s) {
if (Arrays.deepEquals(currentBoard, ((Board) s).getCurrentBoard()))
{
return true;
}
else
return false;
}
private void setOutOfPlace() {
int i = 0;
int j = -1;
do
{
if (j == (columns - 1)) {j = 0; i++;}
else {j++;}
if (currentBoard[i][j] != GOAL[i][j])
{
outOfPlace++;
}
} while (((i+1)*(j+1)) < PUZZLE_SIZE);
}
private int[] getBlankTile()
{
int i = 0;
int j = -1;
int[] blanktile = {0,0};
do
{
if (j == (columns - 1)) {j = 0; i++;}
else {j++;}
if (currentBoard[i][j] == 0) {
blanktile[0] = i;
blanktile[1] = j;
}
} while (((i+1)*(j+1)) < PUZZLE_SIZE);
return blanktile;
}
public int getOutOfPlace()
{
return outOfPlace;
}
private int[][] copyBoard(int[][] state)
{
int[][] returnArray = new int[rows][columns];
for (int i = 0, j = 0; i*j < PUZZLE_SIZE; i++, j++)
{
returnArray[i] = Arrays.copyOf(state[i], state[i].length);
}
return returnArray;
}
private void Swap(int[] nbt, int[] bt, ArrayList<State> children, String direction) {
int[][] cpy = copyBoard(currentBoard);
int temp = cpy[nbt[0]][nbt[1]];
cpy[nbt[0]][nbt[1]] = currentBoard[bt[0]][bt[1]];
cpy[bt[0]][bt[1]] = temp;
children.add(new Board(cpy, this.getGOAL(), this.getRows(), this.getColumns(), (this.getDirections() + direction + ", ")));
}
public int getPUZZLE_SIZE() {
return PUZZLE_SIZE;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public int[][] getGOAL() {
return GOAL;
}
public int[][] getCurrentBoard()
{
return currentBoard;
}
public String getDirections()
{
return directions;
}
}