public int bfs(int maxDepth){ //maxDepth = 3 works.. maxDepth = 4 gives me an error
int src = 0;
int dest = 2;
int nodes = arr[src].length - 1;
boolean[] visited = new boolean[nodes + 1];
int i;
int countDepth = 0;
int countPaths = 0;
int element;
queue.add(src);
while(!queue.isEmpty() || countDepth != maxDepth)
{
element = queue.remove();
i = element;
while(i <= nodes)
{
if(arr[element][i] > 0 && visited[i] == false)
{
queue.add(i);
visited[i] = true;
if(arr[i][element] > 0) //if it has two directions
visited[i] = false;
if(element == dest || i == dest)
countPaths++;
}
i++;
}
countDepth++;
}
return countPaths;
}
I'm trying to go 'x' amount of levels deep while counting the # of paths to the destination.
For some reason I keep getting an error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList.removeFirst(Unknown Source)
at java.util.LinkedList.remove(Unknown Source)
at Graph.bfs(Graph.java:48)
I don't understand what's going on. It seems to work when I go 3 levels deep but when I change it to 4, it doesn't work.
Change
while(!queue.isEmpty() || countDepth != maxDepth)
to
while(!queue.isEmpty() && countDepth != maxDepth)
Each graph has some maximal depth. It seems, you set maxDepth larger than it's really possible for given graph and your loop tries to continue bfsing even after handling all possible nodes (i.e when queue is empty)
UPDATE
I will try to provide answer to your second question you posted in comments even if given information actually is not enough, so, I will try to be extrasens=)
I guess, you are going to calculate all paths of length=1, of length=2.. length=givenMaxDepth|maxPossibleDepth. I saw queue data structure but I didn't see declaration - are you using the same queue for all function calls? If yes, you should clear queue after each call (best place to call queue.clear() is before return statement).
Also, I see you are using new visited array in each call and it's correct but if you actually using some global visited you also should "clear" visited after each call - in other words fill it with false.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to use ArrayDeque for a class that is supposed to have O(1) time complexity for addfront, addback and retrieval. I could only think of using toArray() for retrieval and it is unfortunately O(n). Is there a way to implement a retrieval method for ArrayDeque that is O(1)?
No.
I looked through the source code of ArrayDeque, and in no place is there a method that accesses an arbitrary array element by index. This would have been required in order for the operation to perform in O(1).
It shouldn’t be too hard to implement your own class that fulfils your requirements, though. Search for “circular buffer”. If your array overflows, copy the entire contents into a new array of double size. This can’t be done in constant time, of course, but adding will still be in amortized constant time, the same as for ArrayDeque.
I have assumed that by get() you mean inspecting (without removing) an element by its position/index in the queue counted either from the front or from the back.
Edit
I guess another way would be to use array and find a way to make
addfront constant time but I'm not sure how
Here’s a simple implementation. Please develop further to your need. The ideas are to use a circular buffer and to copy to a new array if the old one gets too small. I believe that ArrayDeque uses the same ideas.
public class MyArrayDeque<E> {
private Object[] elements;
// Index to first element.
private int front = 0;
// Index to first free space after last element.
// back == front means queue is empty (not full).
private int back = 0;
public MyArrayDeque(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Initial capacity must not be negative");
}
// There’s always at least 1 free space, so add 1 to have room for initialCapacity elements
elements = new Object[initialCapacity + 1];
}
public void addFront(E elem) {
checkCapacity();
if (front == 0) {
front = elements.length - 1;
} else {
front--;
}
elements[front] = elem;
}
public void addBack(E elem) {
checkCapacity();
elements[back] = elem;
if (back == elements.length - 1) {
back = 0;
} else {
back++;
}
}
// Makes sure the queue has room for one more element.
private void checkCapacity() {
boolean needToExpand;
if (front == 0) {
needToExpand = back == elements.length - 1;
} else {
needToExpand = back == front - 1;
}
if (needToExpand) {
Object[] newElements = new Object[elements.length * 2];
if (front <= back) {
int size = back - front;
System.arraycopy(elements, front, newElements, 0, size);
front = 0;
back = size;
} else {
int numberOfElementsToCopyFirst = elements.length - front;
System.arraycopy(elements, front, newElements, 0, numberOfElementsToCopyFirst);
System.arraycopy(elements, 0, newElements, numberOfElementsToCopyFirst, back);
front = 0;
back = numberOfElementsToCopyFirst + back;
}
elements = newElements;
}
}
/** Gets the ith element counted from the front without removing it. */
public E get(int i) {
int index = front + i;
if (index >= elements.length) {
index -= elements.length;
}
boolean outOfRange;
if (front <= back) {
outOfRange = index < front || index >= back;
} else {
outOfRange = index >= back && index < front;
}
if (outOfRange) {
throw new ArrayIndexOutOfBoundsException(i);
}
return getInternal(index);
}
#SuppressWarnings("unchecked")
private E getInternal(int index) {
return (E) elements[index];
}
}
For a simple demonstration:
MyArrayDeque<String> queue = new MyArrayDeque<>(1);
queue.addFront("First element added");
queue.addBack("Added at back");
queue.addFront("Added at front");
System.out.println(queue.get(1));
Output is:
First element added
The ArrayDeque API doesn't provide any way to do this.
However, you could write a custom subclass of ArrayDeque that implements get. Something like this:
public E get(int i) {
if (i < 0 || i > size()) {
throw new ....("out of bounds");
}
long pos = this.head + i;
if (pos >= this.elements.length) {
pos -= this.elements.length;
}
return this.elements[(int) pos];
}
Note: this code has not been compiled / debugged. Use at your own risk!
This is O(1) and has no impact on the performance of the existing operations in the ArrayDeque API.
UPDATE
The above won't work as a subclass of the standard ArrayDeque class because the fields it is accessing are package private. However, you could copy the original class and add the above method to the copy.
(Just make sure that you copy the code from the OpenJDK codebase, and satisfy the GPLv2 requirements.)
You could achieve it using additional structure so the space complexity will become O(2n) which might not be very important.
The approach I could suggest is to use a HashMap and to store there an index and link of Object you put to queue. Also, you will need to keep track on first and last index available. Every time you will have to access the element by index - you will have to calculate the shift based on the start index. Of course, you will have to take care to update start and end indexes every time element is added or removed from the queue. The only disadvantage - removal from the middle may take O(n), which might not be critical for the queue case.
Here is an example with states of your objects while using additional structure:
indexMap: {}
startIndex:0
endIndex:0
--> add an element to the head
newCalculatedIndex = startIndex == endIndex ? startIndex : startIndex -1;
//newCalculatedIndex = 0
indexMap: {(0,'A')}
startIndex:0
endIndex:0
--> add an element to the head
//newCalculatedIndex = 0-1 = -1
indexMap: {(-1,'B'), (0,'A')}
startIndex:-1
endIndex:0
--> add an element to the tail
newCalculatedIndex = startIndex == endIndex ? endIndex : endIndex + 1;
//newCalculatedIndex = 0 + 1 = 1
indexMap: {(-1,'B'), (0,'A'), (1,'C')}
startIndex:-1
endIndex:1
--> Access element with index 2:
calculatedIndex = -1 + 2 = 1 -> indexMap.get(1) returns 'C'
I've been grinding leetcode recently and am perplexed on why my solution is timing out when I submit it to Leetcode.
Here is the question:
https://leetcode.com/explore/learn/card/data-structure-tree/133/conclusion/942/
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
Here is my solution that times out in one of the test cases:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0) {
return null; // input error
}
if (postorder == null || postorder.length == 0) {
return null; // input error
}
if (postorder.length != inorder.length) {
return null; // input error
}
List<Integer> inOrder = new ArrayList<Integer>();
List<Integer> postOrder = new ArrayList<Integer>();
for (int i = 0; i < inorder.length; i++) {
inOrder.add(inorder[i]);
postOrder.add(postorder[i]);
}
return buildBinaryTree(inOrder, postOrder);
}
public TreeNode buildBinaryTree(List<Integer> inOrder, List<Integer> postOrder) {
boolean found = false;
int root = 0;
int rootIndex = 0;
// for given in-order scan the post-order right to left to find the root
for (int j = postOrder.size() - 1; j >= 0 && !found; j--) {
root = postOrder.get(j);
if (inOrder.contains(root)) {
rootIndex = inOrder.indexOf(root);
root = inOrder.get(rootIndex);
found = true;
break;
}
}
if (found) {
List<Integer> leftOfRoot = new ArrayList<Integer>();
List<Integer> rightOfRoot = new ArrayList<Integer>();
if (rootIndex > 0) {
leftOfRoot.addAll(inOrder.subList(0, rootIndex));
}
if ((rootIndex + 1) < inOrder.size()) {
rightOfRoot.addAll(inOrder.subList(rootIndex + 1, inOrder.size()));
}
TreeNode node = new TreeNode(root);
node.left = buildBinaryTree(leftOfRoot, postOrder);
node.right = buildBinaryTree(rightOfRoot, postOrder);
return node;
}
return null;
}
}
Can anyone help determine why this is happening? I'm thinking it is the Leetcode judge at fault here and my code is fine.
Leetcode's judge is probably OK. This code is too casual about nested linear array operations and heap allocations. Creating ArrayLists and calling contains, addAll, subList and indexOf may appear innocuous, but they should all be thought of as extremely expensive operations when inside a recursive function that spawns two child calls in every frame.
Let's unpack the code a bit:
List<Integer> inOrder = new ArrayList<Integer>();
List<Integer> postOrder = new ArrayList<Integer>();
for (int i = 0; i < inorder.length; i++) {
inOrder.add(inorder[i]);
postOrder.add(postorder[i]);
}
This is a minor up-front cost but it's an omen of things to come. We've done 2 heap allocations that weren't necessary and walked n. I'd stick to primitive arrays here--no need to allocate objects other than the result nodes. A lookup map for inOrder with value -> index pairs might be useful to allocate if you feel compelled to create a supporting data structure here.
Next, we step into buildBinaryTree. Its structure is basically:
function buildBinaryTree(root) {
// do some stuff
if (not base case reached) {
buildBinaryTree(root.left)
buildBinaryTree(root.right)
}
}
This is linear on the number of nodes in the tree, so it's important that // do some stuff is efficient, hopefully constant time. Walking n in this function would give us quadratic complexity.
Next there's
for (int j = postOrder.size() - 1; j >= 0 && !found; j--) {
root = postOrder.get(j);
if (inOrder.contains(root)) {
rootIndex = inOrder.indexOf(root);
This looks bad, but by definition the root is always the last element in a postorder traversal array, so if we keep a pointer to it, we can remove this outer loop. You can use indexOf directly and avoid the contains call since indexOf returns -1 to indicate a failed search.
The code:
if (found) {
List<Integer> leftOfRoot = new ArrayList<Integer>();
List<Integer> rightOfRoot = new ArrayList<Integer>();
does more unnecessary heap allocations for every call frame.
Here,
leftOfRoot.addAll(inOrder.subList(0, rootIndex));
Walks the list twice, once to create the sublist and again to add the entire sublist to the ArrayList. Repeat for the right subtree for two full walks on n per frame. Using start and end indices per call frame means you never need to allocate heap memory or copy anything to prepare the next call. Adjust the indices and pass a reference to the same two arrays along the entire time.
I recommend running your code with a profiler to see exactly how much time is spent copying and scanning your ArrayLists. The correct implementation should do at most one walk through one of the lists per call frame to locate root in inOrder. No array copying should be done at all.
With these modifications, you should be able to pass, although wrangling the pointers for this problem is not obvious. A hint that may help is this: recursively process the right subtree before the left.
Yes, it would be much faster with arrays. Try this:
public static TreeNode buildTree(int[] inorder, int[] postorder, int start,
int end) {
for (int i = postorder.length-1; i >= 0; --i) {
int root = postorder[i];
int index = indexOf(inorder, start, end, root);
if (index >= 0) {
TreeNode left = index == start
? null
: buildTree(inorder, postorder, start, index);
TreeNode right = index+1 == end
? null
: buildTree(inorder, postorder, index+1, end);
return new TreeNode(root, left, right);
}
}
return null;
}
private static int indexOf(int[] array, int start, int end, int value) {
for (int i = start; i < end; ++i) {
if (array[i] == value) {
return i;
}
}
return -1;
}
I've made a simple 15puzzle game using A-star algorithm with Manhattan Distance.
For easy problems it works, but the solution isn't the optimal one.
For example, if a movement is:
Right->Up
my solution would be:
Right->Up->Left->Down->Right->Up
If i have a hard game to solve, it takes infinite time and get no solution to problem, I think because of this problem.
To implement my game I have followed wikipedia pseudocode of A* algorithm.
Here is my AStar function:
public ArrayList<String> solution(Vector<Integer> start){
ArrayList<String> movePath = new ArrayList<String>(); //Path to solution
PriorityQueue<Node> closedQueue = new PriorityQueue<Node>(500,new Comparator<Node>() {
#Override public int compare(Node a,Node b) {
return a.get_fScore() - b.get_fScore();
}
});
Node node = new Node(start,movePath,heuristic);
int cnt =0;
openQueue.add(node);
while(!openQueue.isEmpty() ) {
//Alt if it takes too much time (ToRemove)
if(cnt == (150)*1000) {
ArrayList<String> noResult = new ArrayList<String>();
noResult.add("Timeout");
return noResult;
}
Node bestNode = openQueue.remove(); //Remove best node from openQueue
closedQueue.add(bestNode); //Insert its to closedQueue
cnt++;
if( cnt % 10000 == 0) {
System.out.printf("Analizzo %,d posizioni. Queue Size = %,d\n", cnt, openQueue.size());
}
//Get first step from bestNode and add to movePath
if(!bestNode.isEmptyMoves()) {
String step = bestNode.get_moves().get(0);
movePath.add(step);
}
//Exit Condition
if(bestNode.get_hScore() == 0) {
return bestNode.get_moves();
}
//Looking for childs
Vector<Node> childs = get_nextMoves(bestNode);
for(int i=0; i<childs.size(); i++) {
if(closedQueue.contains(childs.elementAt(i)))
continue;
childs.elementAt(i).set_gScore(bestNode.get_gScore()+1); //Increment level in tree
if(!openQueue.contains(childs.elementAt(i)))
openQueue.add(childs.elementAt(i));
else {
//!Never reached this level!
System.out.println("Here!");
//TODO Copy child from openQueue to closedQueue
}
}
}
return null;
That is my function to find neighbours:
public Vector<Node> get_nextMoves(Node act){
Vector<Node> steps = new Vector<Node>();
int position = act.get_valuePos(0);
String lastMove = act.get_lastMove();
//System.out.println(lastMove);
//Right Child
if(position + 1 < 16 && position + 1!=3 && position + 1!=7 && position+1 !=11 && lastMove !="Left") {
int temp_pos[] = copyToArray(act.get_posVect());//Copy array of positions of ACT to a temp_pos array
temp_pos[position] = temp_pos[position+1]; //Switch 0 position with Right position
temp_pos[position+1] = 0;
ArrayList<String> temp_moves = new ArrayList<String>();
for(int i=0; i<act.get_moves().size(); i++) {
temp_moves.add(act.get_moves().get(i)); //Save old steps
}
temp_moves.add("Right");//And add new one
Node child = new Node(temp_pos,temp_moves,act.get_heuristic()); //New Node
steps.addElement(child);//Added to vector
}
//Left Child
if(position - 1 >= 0 && position - 1 != 4 && position - 1 != 8 && position - 1 != 12 && lastMove !="Right") {
int temp_pos[] = copyToArray(act.get_posVect());
temp_pos[position] = temp_pos[position-1];
temp_pos[position-1] = 0;
ArrayList<String> temp_moves = new ArrayList<String>();
for(int i=0; i<act.get_moves().size(); i++) {
temp_moves.add(act.get_moves().get(i));
}
temp_moves.add("Left");
Node child = new Node(temp_pos,temp_moves,act.get_heuristic());
steps.addElement(child);
}
//Up Child
if(position - 4 >= 0 && lastMove !="Down") {
int temp_pos[] = copyToArray(act.get_posVect());
temp_pos[position] = temp_pos[position-4];
temp_pos[position-4] = 0;
ArrayList<String> temp_moves = new ArrayList<String>();
for(int i=0; i<act.get_moves().size(); i++) {
temp_moves.add(act.get_moves().get(i));
}
temp_moves.add("Up");
Node child = new Node(temp_pos,temp_moves,act.get_heuristic());
steps.addElement(child);
}
//Down Child
if(position + 4 < 16 && lastMove !="Up") {
int temp_pos[] = copyToArray(act.get_posVect());
temp_pos[position] = temp_pos[position+4];
temp_pos[position+4] = 0;
ArrayList<String> temp_moves = new ArrayList<String>();
for(int i=0; i<act.get_moves().size(); i++) {
temp_moves.add(act.get_moves().get(i));
}
temp_moves.add("Down");
Node child = new Node(temp_pos,temp_moves,act.get_heuristic());
steps.addElement(child);
}
return steps;
And that is my ManhattanDistance function:
public int calcolaDist(Vector<Integer> A) {
int result = 0;
Vector<Integer> goal_Mat = initialize_Mat();
for(int i=0; i<16; i++) {
int x_goal = (goal_Mat.indexOf(i))/4;
int y_goal = (goal_Mat.indexOf(i))%4;
int x_def = (A.indexOf(i))/4;
int y_def = (A.indexOf(i))%4;
if(A.elementAt(i) > 0) {
result += Math.abs(x_def - x_goal);
result += Math.abs(y_def - y_goal);
}
}
return result;
If my puzzle is:
start = {1,3,0,4,5,2,7,8,9,6,10,11,13,14,15,12}
My solution will be:
[Left, Down, Down, Right, Down, Right, Up, Left, Down, Right, Up, Left, Down, Right]
I know that using Vectors isn't a good choice and my code is "a little" dirty, but I'm going to clean its as soon as I get out of that problem!
Thank you all!
First, I see a bit of confusion in your code with the OPEN and CLOSED queues. The OPEN queue should be the one that manages the priority of the nodes (PriorityQueue). This is not needed for CLOSED, which only stores the visited nodes and their cost (maybe your algorithm will be more efficient changing CLOSED by a HashSet or HashMap to avoid ordering the nodes in CLOSED as well). I can't see in your code how you initialized the OPEN queue, but maybe that is one issue with your implementation of A*.
The other issue I see with your code is that with A*-based algorithms, you need to manage the situation in which you reach a node that is already in OPEN/CLOSED, but with a different cost. This can happen if you visit a node from different parents, or you enter in a loop. The algorithm will not work properly if you are not taking that into account.
If you visit a node that is already in the OPEN queue, and the new node has a lower f-score, you should remove the old node from OPEN and insert the one with the lower cost.
If the node has a higher cost (in OPEN or CLOSED) then you should simply discard that node to avoid loops.
The problem is though, but the state space is finite and the algorithm should finish at some point. I see that your implementation is in Java. Maybe it would be helpful for you if you take a look to the library Hipster4j, which has an implementation of A*, and an example solving the 8-puzzle.
I hope my answer helps. Good luck!
The nature of this problem has changed since submission, but the question isn't fit for deletion. I've answered the problem below and marked it as a community post.
I'm writing a recursive path-navigating function and the final piece I need involves knowing which cell you came from, and determining where to go next.
The Stage
You are given a 2d array where 0's denote an invalid path and 1's denote a valid path. As far as I know, you are allowed to manipulate the data of the array you're navigating, so I mark a traveled path with 2's.
The Goal
You need to recursively find and print all paths from origin to exit. There are four mazes, some with multiple paths, dead ends, or loops.
I've written code that can correctly handle all three cases, except the method for finding the next path is flawed in that it starts at a fixed location relative to your current index, and checks for a travelled path; If you encounter it, it's supposed to retreat.
While this works in most cases, it fails in a case when the first place it checks happens to be the place you came from. At this point, it returns out and ends prematurely.
Because of this, I need to find a way to intelligently start scanning (clockwise or anti-clockwise) based on where you came from, so that that place is always the last place checked.
Here is some code describing the process (note: edge cases are handled prior to this, so we don't need to worry about that):
private static void main()
{
int StartX = ;//Any arbitrary X
int StartY = ;//Any arbitrary Y
String Path = ""; //Recursive calls will tack on their location to this and print only when an exit path is found.
int[][] myArray = ;//We are given this array, I just edit it as I go
Navigator(StartX, StartY, Path, myArray);
}
private static void Navigator(int locX, int locY, String Path, int[][] myArray)
{
int newX = 0; int newY = 0;
Path = Path.concat("["+locX+","+locY+"]");
//Case 1: You're on the edge of the maze
boolean bIsOnEdge = (locX == 0 || locX == myArray.length-1 || locY == 0 || locY == myArray[0].length-1);
if (bIsOnEdge)
{
System.out.println(Path);
return;
}
int[][] Surroundings = surroundingsFinder(locX, locY, myArray);
for (int i = 0; i <= 7; i++)
{
//Case 2: Path encountered
if (Surroundings[0][i] == 1)
{
myArray[locX][locY] = 2;
newX = Surroundings[1][i];
newY = Surroundings[2][i];
Navigator(newX, newY, myArray, Path);
}
//Case 3: Breadcrumb encountered
if (Surroundings[0][i] == 2)
{
myArray[locX][locY] = 1;
return;
}
}
}
//generates 2D array of your surroundings clockwise from N to NW
//THIS IS THE PART THAT NEEDS TO BE IMPROVED, It always starts at A.
//
// H A B
// G - C
// F E D
//
static int[][] surroundingsFinder(int locX, int locY, int[][] myArray)
{
int[][] Surroundings = new int[3][8];
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
}
}
//Can be done simpler, is done this way for clarity
int xA = locX-1; int yA = locY; int valA = myArray[xA][yA];
int xB = locX-1; int yB = locY+1; int valB = myArray[xB][yB];
int xC = locX; int yC = locY+1; int valC = myArray[xC][yC];
int xD = locX+1; int yD = locY+1; int valD = myArray[xD][yD];
int xE = locX+1; int yE = locY; int valE = myArray[xE][yE];
int xF = locX+1; int yF = locY-1; int valF = myArray[xF][yF];
int xG = locX; int yG = locY-1; int valG = myArray[xG][yG];
int xH = locX-1; int yH = locY-1; int valH = myArray[xH][yH];
int[][] Surroundings = new int[3][8];
Surroundings[0][0] = valA; Surroundings[1][0] = xA; Surroundings[2][0] = yA;
Surroundings[0][1] = valB; Surroundings[1][1] = xB; Surroundings[2][1] = yB;
Surroundings[0][2] = valC; Surroundings[1][2] = xC; Surroundings[2][2] = yC;
Surroundings[0][3] = valD; Surroundings[1][3] = xD; Surroundings[2][3] = yD;
Surroundings[0][4] = valE; Surroundings[1][4] = xE; Surroundings[2][4] = yE;
Surroundings[0][5] = valF; Surroundings[1][5] = xF; Surroundings[2][5] = yF;
Surroundings[0][6] = valG; Surroundings[1][6] = xG; Surroundings[2][6] = yG;
Surroundings[0][7] = valH; Surroundings[1][7] = xH; Surroundings[2][7] = yH;
return Surroundings;
}
Can anyone help me with this? As you can see, surroundingsFinder always finds A first, then B all the way to H. This is fine if and only if you entered from H. But if fails on cases where you entered from A, so I need to make a way to intelligently determine where to start finding. Once I know this, I can probably adapt the logic so I no longer use a 2D array of values, as well. But so far I can't come up with the logic for the smart searcher!
NOTE: I am aware that Java does not optimize middle-recursion. It seems impossible to get tail recursion working for a problem like this.
The Solution
The initial goal was to print, from start to end, all of the paths that exit the array.
An earlier rendition of the script wrote "0" on treaded locations rather than "2", but for some reason I imagined that I needed the "2" and I needed to differentiate between "treaded path" and "invalid path".
In fact, due to the recursive nature of the problem, I discovered that you can in fact solve the problem writing only 0's as you go. Also, I no longer needed to keep track of where I came from and instead of checking clockwise over a matrix, I was iterating from left to right down the 3x3 matrix surrounding me, skipping my own cell.
Here is the completed code for such a solution. It prints to console upon finding an exit (edge) and otherwise traces itself around the maze, complete with recursion. To start the function, you are given a square 2D array of 0's and 1's where 1 is a valid path and 0 is invalid. You are also given a set of coordinates where you are "dropped in" (locX, locY) and an empty string that accumulates coordinates, forming a path that is later printed out (String Path = "")
Here is the code:
static void Navigator(int locX, int locY, int[][] myArray, String Path)
{
int newX = 0;
int newY = 0;
Path = Path.concat("["+locX+","+locY+"]");
if ((locX == 0 || locX == myArray.length-1 || locY == 0 || locY == myArray[0].length-1))
{//Edge Found
System.out.println(Path);
pathCnt++;
myArray[locX][locY] = 1;
return;
}
for (int row = -1; row <= 1; row++)
{
for (int col = -1; col <= 1; col++)
{
if (!(col == 0 && row == 0) && (myArray[locX+row][locY+col] == 1))
{ //Valid Path Found
myArray[locX][locY] = 0;
Navigator(locX+row, locY+col, myArray, Path);
}
}
}
//Dead End Found
myArray[locX][locY] = 1;
return;
} System.out.println(Path);
pathCnt++;
swamp[locX][locY] = 1;
return;
}
for (int row = -1; row <= 1; row++)
{
for (int col = -1; col <= 1; col++)
{
if (!(col == 0 && row == 0) && (swamp[locX+row][locY+col] == 1))
{ //Valid Path Found
swamp[locX][locY] = 0;
Navigator(locX+row, locY+col, swamp, Path);
}
}
}
//Dead End Found
swamp[locX][locY] = 1;
return;
}
As you may determine yourself, every time we "enter" a cell, we have 8 neighbors to check for validity. First, to save on run time and to avoid going out of the array during our for loop (it can't find myArray[i][j] if i or j point it outside, and it will error out), we check for edges. Since we're given the area of our swamp we use a truth comparison statement that essentially says ("(am I on the top or left edge?) or (am I on the bottom or right edge?)"). If we ARE on an edge, we print out the Path we're holding (thanks to deep copy, we have a unique copy of the original Path that only prints if we're on an edge, and includes our full set of coordinates).
If we aren't on an edge, then we start looking around us. We start at top left and move horizontally to bottom right, with a special check to make sure we're not checking where we're standing.:
A B C
D . E
F G H
This loop checks only for 1's and only calls the function up again should that happen. Why? Because it is the second-to-last case. There is only one extra situation that will occur, and if we reach the end of the function it means we hit that case. Why write extra code (checking for 0's to specifically recognize it?
So, as I just mentioned, if we exit the for loop, it means we didn't encounter any 1's at all. It means we're surrounded by zeros! It means we've hit a dead end, and that means that all we have to do is error our away out of that instance of the function, ergo the final return;.
All in all, the final function is simple. But coming from no background and having to realize the patterns and meanings of these cases, and after several failed attempts at this, it can take quite a bit of work. I was several days at work on perfecting this.
Happy coding, Everyone!
Your issue seems to be with:
if (Surroundings[0][i] == 2)
{
myArray[locX][locY] = 1;
return;
}
Perhaps this should be changed to:
if (Surroundings[0][i] == 2)
{
// not sure why you need this if it's already 1
myArray[locX][locY] = 1;
// go to next iteration of the "i" loop
// and keep looking for next available path
continue;
}
Your recursive method will automatically return when none of the surrounding cells satisfy the condition if (Surroundings[0][i] == 1).
PS: It's conventional to name your variables using small letter as the first character. For example: surroundings, path, startX or myVar
I'm trying to implement a Min Heap in Java, but I'm having issues with inserting and removing elements (inserting at the end, removing the root as min). It seems to work for the most part (I use a program to visually display the heap and have been printing out the new roots when min has been removed, things like that).
My problem is, for some reason the root won't switch with a new item when a new item is added, but I can't figure out why at all. Also, it seems this is only the problem when there are a lot of duplicates, the heap doesn't seem completely capable of staying in order (the parent is smaller than the children). For the most part, it does. Only occasionally it doesn't, and to me it seems random.
This is done with generics, and basically following most algorithms. Everything else I know for a fact works, it's definitely a problem with these two methods.
public void insert(T e) {
if (size == capacity)
increaseSize(); //this works fine
last = curr; //keeping track of the last index, for heapifying down/bubbling down when removing min
int parent = curr/2;
size++; //we added an element, so the size of our data set is larger
heap[curr] = e; //put value at end of array
//bubble up
int temp = curr;
while (temp > 1 && ((Comparable<T>) heap[temp]).compareTo(heap[parent]) < 0) { //if current element is less than the parent
//integer division
parent = temp/2;
swap(temp, parent); //the swapping method should be correct, but I included it for clarification
temp = parent; //just moves the index value to follow the element we added as it is bubbled up
}
curr++; //next element to be added will be after this one
}
public void swap(int a, int b){
T temp = heap[a];
heap[a] = heap[b];
heap[b] = temp;
}
public T removeMin() {
//root is always min
T min = heap[1];
//keep sure array not empty, or else size will go negative
if (size > 0)
size--;
//put last element as root
heap[1] = heap[last];
heap[last] = null;
//keep sure array not empty, or else last will not be an index
if (last > 0)
last--;
//set for starting at root
int right = 3;
int left = 2;
int curr = 1;
int smaller = 0;
//fix heap, heapify down
while(left < size && right < size){ //we are in array bounds
if (heap[left] != null && heap[right] != null){ //so no null pointer exceptions
if (((Comparable<T>)heap[left]).compareTo(heap[right]) < 0) //left is smaller
smaller = left;
else if (((Comparable<T>)heap[left]).compareTo(heap[right]) > 0) //right is smaller
smaller = right;
else //they are equal
smaller = left;
}
if (heap[left] == null || heap[right] == null)//one child is null
{
if (heap[left] == null && heap[right] == null)//both null, stop
break;
if (heap[left] == null)//right is not null
smaller = right;
else //left is not null
smaller = left;
}
if (((Comparable<T>)heap[curr]).compareTo(heap[smaller]) > 0)//compare smaller or only child
{
swap(curr,smaller); //swap with child
curr = smaller; //so loop can check new children for new placement
}
else //if in order, stop
break;
right = 2*curr + 1; //set new children
left = 2*curr;
}
return min; //return root
}
Any variables not declared in the methods are global, and I know a couple of things are probably redundant, like the whole current/last/temp situation in add, so I'm sorry about that. I tried to make all names self explanatory and explain all the checks I did in removeMin. Any help would be insanely appreciated, I've gotten as far as I can looking things up and debugging. I think I'm just fundamentally missing something here.
Just to help you debug, you should simplify the code. There is something strange going on with 'last' variable. Also in 'insert' when you do the loop, probably temp should go to 0, that is
while (temp >= 0 &&......