Java finding full routes in NxN grid [duplicate] - java

This question already has answers here:
How do I do a deep copy of a 2d array in Java?
(7 answers)
Closed 8 years ago.
So I am trying to make an algorithm for finding full paths in NxN grid. For example in 1x1 grid there is 1 possible path, in 2x2 grid there is 1, in 3x3 there is 2 and in 4x4 there is 8. The idea is to find scenarios where we can fill every spot of the grid by moving.
I have made a recursive function for the job and here is the code:
public static int getRoutesHelp(int[][] table, int x, int y)
{
if(x > table.length-1 || x < 0 || y < 0 || y > table.length-1)
return 0;
if(table[x][y] == 1)
return 0;
table[x][y] = 1;
if(isDeadEnd(table, x, y))
{
if(isTableFull(table))
return 1;
}
else
{
int a = getRoutesHelp(table, x-1, y);
int d = getRoutesHelp(table, x, y+1);
int b = getRoutesHelp(table, x+1, y);
int c = getRoutesHelp(table, x, y-1);
return a+b+c+d;
}
return 0;
}
public static int getRoutes(int size)
{
int[][] table = new int[size][size];
// init table
for(int i = 0; i < size; i++)
{
for(int a = 0; a < size; a++)
{
table[i][a] = 0;
}
}
return getRoutesHelp(table, 0 ,0);
}
So basically I start from 0.0 and start moving to all possible directions and by repeating this I get the amount of successful routes. The problem is that after the assignment of int d the original table is somehow filled with 1 but it should be empty as far as I understand because java passes a copy of the table right? I've been fighting with this for like 4 hours and can't really find the problem so any help is appreciated. Empty slots in table are marked with 0 and filled slots with 1.
EDIT: I managed to fix the issue I had with the copying and now my other problem is that with 5x5 grid my algorithm returns 52 routes and it should be 86. So it works with 4x4 grid okay, but once I move further it breaks.
Added the isDeadEnd function here
public static boolean isDeadEnd(int[][] table, int x, int y)
{
int toCheck[] = new int[4];
toCheck[0] = x-1; // left
toCheck[1] = y-1; // top
toCheck[2] = x+1; // right
toCheck[3] = y+1; // bottom
int valuesOfDirections[] = new int[4]; // left, top, right, bottom
for(int i = 0; i < 4; i++)
{
int tarkastettava = toCheck[i];
if(tarkastettava > table.length-1 || tarkastettava < 0)
{
valuesOfDirections[i] = 1;
}
else
{
if(i == 0 || i == 2)
{
valuesOfDirections[i] = table[tarkastettava][y];
}
else
{
valuesOfDirections[i] = table[x][tarkastettava];
}
}
}
for(int i = 0; i < 4; i++)
{
if(valuesOfDirections[i] == 0)
{
return false;
}
}
return true;
}

Come to think of it, you probably can do a simple backtrack here:
table[x][y] = 1;
if(isDeadEnd(table, x, y)) {
if(isTableFull(table))
return 1;
}
table[x][y] = 0;
}
And later:
int res = a + b + c + d;
if (res == 0) {
// backtrack here too
table[x][y] = 0;
}
return res;

Related

How to find circumference and area of a 2D shape whose indices are given as 0 or 1 in a 2D array?

Given a 2D array of size 20x20 whose values resemble a 2D shape, for example a square or rectangle:
public static int[][] rectangle= {
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
};
I would like to find its circumference and area in an algorithm that does the following:
Finds the nearest (1) point starting from the center (point[10][10]).
Uses the nearest (1) point as a starting point to iterate over all the remaining 1s to count the
circumference.
calculates the number of zeros enclosed by the circumference to calculate the area
Now below is where I am currently at; the "guess" method calculates the nearest (1) point and executes the "count" method which then calculates the circumference.
public static void guess() {
boolean found = false;
if(!found) {
int y = 10;
for(int x = 10; x <= 20; x++) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y++]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
if(!found) {
int y = 10;
for(int x = 10; x >= 0; x--) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y--]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
if(!found) {
int x = 10;
for(int y = 10; y <= 20; y++) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y++]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
if(!found) {
int x = 10;
for(int y = 10; y >= 0; y--) {
if(rectangle[x][y]==1) {
rectangle[x][y] = 2;
found = true;
break;
}else if(rectangle[x][y--]==1) {
rectangle[x][y] = 2;
found = true;
break;
}
}
}
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
if(rectangle[i][j] == 2) {
Count(i, j);
break;
}
}
}
}
public static void Count(int x, int y) {
public int circumf;
int tx = x;
int ty = y;
for(int c = 40; c >=0; c--) {
if((c/2)-1<0 || x>=20 || x<0 || y>=20 || y<0) break;
if(rectangle[x][(int) (c/2)-1]==1 || rectangle[(int) (c/2)-1][y]==1
|| rectangle[x++][y]==1 || rectangle[x][y++]==1
|| rectangle[x--][(int) (c/2)-1]==1 || rectangle[(int) (c/2)-1][y--]==1 || rectangle[x--][y]==1 || rectangle[x][y--]==1) {
circumf++;
}
}
x = tx;
y = ty;
for(int c = 0; c <=40; c++) {
if((c/2)>=20 || x>=20 || x<0 || y>=20 || y<0) break;
if(rectangle[x][(int) (c/2)]==1 || rectangle[(int) (c/2)][y]==1
|| rectangle[x++][y]==1 || rectangle[x][y++]==1
|| rectangle[x--][(int) (c/2)]==1 || rectangle[(int) (c/2)]
[y--]==1 || rectangle[x--][y]==1 || rectangle[x][y--]==1) {
circumf++;
}
}
System.out.print(circumf);
Now, the guess method calculates the nearest point correctly, however the count method doesn't correctly counts the circumference which is close to 70 in the above example.
As for the area calculating algorithm, I still didn't quite figure it out.
The above code isn't the most brilliant or organized thing I know, but any help would be really appreciated!
Suppose you find the nearest one at index [i][j]. You need to check the nearest values in a cross pattern since your object is a rectangle.
For example you are in the middle one in the left edge of the rectangle:
0 1 0
0 1 0
0 1 0
You check were the 1's "continue" finding thus the edge direction. There are 2 possible outcomes either
[x-1][y]=[x][y]=[x+1][y] or [x][y-1]=[x][y]=[x][y+1]==1
So,you found that the edge is vertical. Continue iterating through this verical line until the condition [x][y-1]==1 is false. Then do the same thing for the horizontal line.
Now for the 0's count you could store the index i,j of all the corners while you are doing the above check.If you know their positions and the size of the array is fixed you can calculate the 0's like:
0's area = [(DL_corner_index - 1) - (UL_corner_index + 1)] x [(UR_corner_index - 1) - (UL_corner_index + 1)]
int rectangle[10][10] ={
{0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,1,1,1,1,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,0,0,0,0,0,0,1,0},
{0,1,1,1,1,1,1,1,1,0},
{0,0,0,0,0,0,0,0,0,0}
};
//calculating area of zeros with known corner coordinates
//you have stored the coordinates in variables like this
int UL_X=1,UR_X=8;
int UL_Y=1,DL_Y=8;
int area = ((UR_X-1) - UL_X)*((DL_Y-1)-UL_Y);
cout<<area; //36
}

Mark numbers for sudoku game

im currently programming a sudoku game in java. I created a 2 dimensional array as the playingfield. Now i want to write a method, which saves numbers for a given position in the playingfield, for example i want to save the numbers 9 and 4 at the position (3,5) in the field. I've thought about to create an array for the position and save the numbers there, i've tried that but i really dont know how to do it. I searched some sites for my problem but i couldnt find solution for it. I hope someone can help me with that.
public byte[][] sudoku = new byte[9][9];
public SudokuField(byte[][] sudoku){
if(sudoku.length != 9){
System.exit(2);
}
for(int i = 0; i < sudoku.length; i++){
if(sudoku[i].length > 9){
System.exit(2);
}
}
this.sudoku = sudoku;
}
public boolean checkColumn(int x, int y, byte value){
boolean check = true;
for(int i = 0; i < this.sudoku.length; i++){
if(this.sudoku[i][y] == value){
check = false;
}
}
return check;
}
public boolean checkRow(int x, int y, byte value){
boolean check = true;
for(int i = x; i < x + 1; i++){
for(int j = 0; j < this.sudoku[i].length; j++){
if(this.sudoku[i][j] == value){
check = false;
}
}
}
return check;
}
public boolean checkSquare(int x, int y, byte value){
boolean check = true;
x = (int)(x / 3) * 3;
y = (int)(y / 3) * 3;
for(int i = x; i < x + 3; i++){
for(int j = y; j < y + 3; j++){
if(this.sudoku[i][j] == value){
check = false;
}
}
}
return check;
}
public void setCell(int x, int y, byte value){
if(x < 0 || x > 9 || y < 0 || y > 9){
System.out.println("Invalid Number");
}else if(checkRow(x,y, value) && checkColumn(x,y,value) && checkSquare(x, y, value)){
this.sudoku[x][y] = value;
}else{
System.out.println("Invalid cell");
}
}
public byte getCell(int x, int y){
return this.sudoku[x][y];
}
public void markCell(int x, int y, byte value){
}
So this is the code i wrote so far. Im currently working on markCell, which saves numbers at a position u might want to put into the position. So my idea is to create an array for the position, to store these numbers in it.

Why the dynamic programming solution only works for squre board?

The problem is:
Given exact k steps, how many ways to move a point from start point to destination? Point can move for eight directions(horizontally, vertically, diagonally, anti-diagonally).
I solved the problem through DP, but it works only for square board, not for rectangle board. I mean if dim[0]!=dim[1] in the code, it will run into an error result.
Here I can provide test case:
Test case 1
dim = {5,6},start = {0,2},end = {2,2},steps = 4;
result is 50(expected: 105)
Test case 2
dim = {5,5},int[] start = {0,2},end = {2,2},steps = 4;
result is 105(expected: 105)
Here is the code:
private static int[][] dir = {{0,1},{1,0},{1,1},{1,-1},{0,-1},{-1,0},{-1,-1},{-1,1}};
//DP
/*
#param dim, a tuple (width, height) of the dimensions of the board
#param start, a tuple (x, y) of the king's starting coordinate
#param target, a tuple (x, y) of the king's destination
*/
public static int countPaths2(int[] dim, int[] start, int[] des, int steps){
if(dim[0] == 0 || dim[1] == 0) return 0;
int[][][] dp = new int[dim[0]*dim[1]][dim[1]*dim[0]][steps+1];
for(int step = 0; step<=steps;step++){
for(int i = 0; i< dim[0]*dim[1];i++){
for(int j = 0; j< dim[0]*dim[1];j++){
if(step == 0 && i == j){
dp[i][j][step] = 1;
}
if(step >= 1){
for(int k =0; k< dir.length;k++){
int row = i / dim[0];
int col = i % dim[1];
if(row + dir[k][0] >= 0 && row + dir[k][0]< dim[0] && col + dir[k][1]>=0 && col + dir[k][1]< dim[1]){
int adj = (row + dir[k][0])*dim[0] + col + dir[k][1];
dp[i][j][step] += dp[adj][j][step-1];
}
}
}
}
}
}
int startPos = start[0]*dim[0] + start[1];
int targetPos = des[0]*dim[0] + des[1];
return dp[startPos][targetPos][steps];
}
public static void main(String[] args){
int[] dim = {5,5}; // can just use to square;
int[] start = {0,2};
int[] end = {2,2};
int steps = 7;
System.out.println(countPaths2(dim, start,end, steps));
}
How could I make it work for any kind of board?
The culprit is:
int row = i / dim[0];
int col = i % dim[1]; // <- this should have been dim[0]
in the div/mod pattern you are supposed to divide and modulo by the same number...

Calculating next frame in conways game of life using java

trying to create a Conways Game of life, but apparently the shapes are not like they have to be. Perhaps someone can help me find the issue.
For example the glider :
- X - - - -
- - X X - -
- X X - - -
- - - - - -
becomes this
- - X X - -
- X - - - -
X X X - - -
- X X X - -
but should be like this :
- - X - - -
- - - X - -
- X X X - -
- - - - - -
And my code looks like this
public Frame(int x, int y) {
setWidth(x);
setHeight(y);
if (x<1)
frame = null;
else if (y<1)
frame = null;
else {
frame = new String [x][y];
for (int i=0; i<frame.length; i++) {
for (int j=0; j<frame[i].length; j++) {
frame [i][j] = DEAD;
}
}
} // else
} // construktor
public Integer getNeighbourCount(int x, int y) {
Frame cell = new Frame(getHeight(), getWidth());
int counter = 0;
if(frame[x][y].equals(ALIVE))
{
counter = counter - 1;
}
for(int i=x-1; i<=x+1;i++){
if(i<frame.length && i>0){
for(int j=y-1; j<=y+1;j++){
if(j<frame[i].length && j>0){
if (frame[i][j]==ALIVE) {
counter++;
}
}
}
}
}
return counter;
}
public Frame nextFrame() {
// Returns next frame
Frame cell = new Frame(getWidth(), getHeight());
//cell.frame = new String[getWidth()][getHeight()];
for(int i = 0; i < frame.length; i++){
for(int j =0; j <frame[i].length;j++){
int n = getNeighbourCount(i,j);
if(cell.frame[i][j]==null) {
cell.frame[i][j] = DEAD;
}
if (isAlive(i, j) && n < 2 || n > 3) {
cell.frame[i][j] = DEAD;
}
if (isAlive(i, j) && n == 3 || n == 2){
cell.frame[i][j] = ALIVE;
}
if(!isAlive(i, j) && n == 3) {
cell.frame[i][j] = ALIVE;
}
if(isAlive(i, j) && n > 3){
cell.frame[i][j] = DEAD;
}
frame[i][j] = cell.frame[i][j];
}
}
cell.toString();
return cell;
}
`
Full code http://pastebin.com/LMwz724H
Here's a solution that works - using an enum for each cell and getting the i/j and x/y stuff right (I think). It certainly generates the correct first iteration:
static class GameOfLife {
final int w;
final int h;
State[][] frame;
enum State {
Dead, Alive;
}
public GameOfLife(int w, int h) {
this.w = w;
this.h = h;
frame = new State[h][w];
}
public void alive(int x, int y) {
frame[y][x] = State.Alive;
}
public void tick() {
frame = nextGeneration();
}
private int surroundingPopulation(int x, int y) {
int pop = 0;
for (int i = y - 1; i <= y + 1; i++) {
for (int j = x - 1; j <= x + 1; j++) {
// On frame - vertically.
if ((i >= 0 && i < h)
// On frame horizontally.
&& (j >= 0 && j < w)
// Alive
&& (frame[i][j] == State.Alive)
// Not the center.
&& (i != y || j != x)) {
pop += 1;
}
}
}
return pop;
}
private State[][] nextGeneration() {
State[][] next = new State[h][w];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int pop = surroundingPopulation(x, y);
// Any live cell
if (frame[y][x] == State.Alive) {
if (pop < 2) {
// ... with fewer than two live neighbours dies, as if caused by under-population.
next[y][x] = State.Dead;
} else if (pop > 3) {
// ... with more than three live neighbours dies, as if by overcrowding.
next[y][x] = State.Dead;
} else {
// ... with two or three live neighbours lives on to the next generation.
next[y][x] = State.Alive;
}
} else {
// Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
if (pop == 3) {
next[y][x] = State.Alive;
}
}
}
}
return next;
}
#Override
public String toString() {
StringBuilder s = new StringBuilder();
for (State[] row : frame) {
for (State c : row) {
s.append(c == State.Alive ? "X" : " ");
}
s.append("\r\n");
}
return s.toString();
}
}
public void test() {
GameOfLife g = new GameOfLife(6, 6);
g.alive(1, 0);
g.alive(2, 1);
g.alive(3, 1);
g.alive(1, 2);
g.alive(2, 2);
System.out.println("Before:\r\n" + g);
g.tick();
System.out.println("After:\r\n" + g);
}
I believe the problem is that you are copying the new value as you iterate through the loop. This means neighbours are using the value from the next tick rather than the current one.
You can fix this by waiting until you calculated all new values in your new frame: cell.frame and then iterate through the frame again and copy from cell.frame to frame.
An alternative (better in my view) is to have away of cloning a frame during construction. Then you could change your nextFrame method to create a clone of frame and use the clone to set the new values in frame.
You are changing the DEAD and ALIVE frames while you iterate through the grid. You need to store the coordinates which should die or become alive and perform that afterwards.
Store the coordinates in two ArrayLists (dead, alive). The first and second position is the x and y axis, and change those coordinates according to whether they should become alive or not.
Here's a snippet from a simple test I wrote a while back. As others have mentioned, don't change values on an active board while still reading them. Instead, clone the board and make changes to the copy while reading the current board.
Another problem I bumped into a few times was iterating over y, then x for each y, but referring to x,y when accessing a point. It feels back to front :)
// Rules:
// 1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.
// 2) Any live cell with two or three live neighbours lives on to the next generation.
// 3) Any live cell with more than three live neighbours dies, as if by overcrowding.
// 4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
void mutateGrid() {
// Copy existing grid into the next generation's grid
boolean[][] mutatedGrid = new boolean[gridXWidth][gridYHeight];
for (int i = 0; i < gridXWidth; i++) {
System.arraycopy(grid[i], 0, mutatedGrid[i], 0, gridYHeight);
}
// Start mutation rules
for (int y = 0; y < gridYHeight; y++) {
for (int x = 0; x < gridXWidth; x++) {
int liveNeighbours = countLiveNeighbours(x,y);
if (liveNeighbours < 2 || liveNeighbours > 3) {
mutatedGrid[x][y] = false;
}
else if (liveNeighbours == 3) {
mutatedGrid[x][y] = true;
}
}
}
grid = mutatedGrid;
}
int countLiveNeighbours(int x, int y) {
int count = 0;
for (int j = y-1; j <= y+1; j++) {
for (int i = x-1; i <= x+1; i++) {
if (i < 0 || j < 0 || i >= gridXWidth || j >= gridYHeight){
continue;
}
if (grid[i][j]) {
count++;
}
}
}
count -= grid[x][y]?1:0; // remove self from count
return count;
}

Maze not working?

code:
Array is a predefined boolean array that I made, and val is the length of the array (it is a square). I use it as a starting point, rather than using a random value
import java.util.*;
import javax.swing.*;
public class Main
{
public void main()
{
String Val = JOptionPane.showInputDialog("Enter the number of rows/columns");
int x = Integer.parseInt(Val);
boolean mazeArch[][] = new boolean [x][x];
BoundariesDeclared(mazeArch, x);
generateMaze(mazeArch, x);
convertArray(mazeArch, x);
}
public void printArray(String Array[][]) // Prints out the array
{
for (int i =0; i < Array.length; i++) {
for (int j = 0; j < Array.length; j++) {
System.out.print(" " + Array[i][j]);
}
System.out.println("");
}
}
public void convertArray(boolean Array[][], int z)
{
String RealArray[][] = new String [z][z];
for(int x = 0; x < Array.length; x++)
{
for(int y = 0; y < Array.length; y++)
{
if(Array[x][y] == true)
{
RealArray[x][y] = "*";
}
if(Array[x][y] == false)
{
RealArray[x][y] = " ";
}
}
}
printArray(RealArray);
}
public void BoundariesDeclared(boolean Array[][], int y)
{
for(int x = 0; x < Array.length; x++)
Array[0][x] = true;
for (int x = 0; x < Array.length; x++)
Array[x][0] = true;
for (int x = 0; x < Array.length; x++)
Array[x][Array.length-1] = true;
for (int x = 0; x < Array.length; x++)
Array[Array.length-1][x] = true;
}
public void generateMaze(boolean Array[][], int val)
{
Stack<Integer> StackX = new Stack<Integer>();
Stack<Integer> StackY = new Stack<Integer>();
int x = val / 2; // Start in the middle
int y = val / 2; // Start in the middle
StackX.push(x);
StackY.push(y);
while(!StackX.isEmpty())
{
Array[x][y] = true; // is Visited
x = StackX.peek();
y = StackY.peek();
if(Array[x][y+1] == false)
{
StackX.push(x);
StackY.push(y+1);
y = y + 1;
}
else if(Array[x][y-1] == false)
{
StackX.push(x);
StackY.push(y-1);
y = y - 1;
}
else if(Array[x+1][y] == false)
{
StackX.push(x+1);
StackY.push(y);
x = x+1;
}
else if(Array[x-1][y] == false)
{
StackX.push(x-1);
StackY.push(y);
x = x-1;
}
else
{
StackX.pop();
StackY.pop();
}
}
}
}
Whenever I print the results, I only get stars, which mean that every single boolean is set to true. I understand my error, because I am visiting every spot the result will be that they are all set to true. But what can i do to fix this? I think I have the concept correct, just not the application. I previously asked the question and was told that I need to make two Arrays (1 for walls, another for visiting) but how would I apply this as well?
You didn't mention what are you trying to do. So not much we can help.
What is this maze doing?
What's your input?
What's your expected result?
Add this line and debug yourself.
public void generateMaze(boolean Array[][], int val) {
Stack<Integer> StackX = new Stack<Integer>();
Stack<Integer> StackY = new Stack<Integer>();
int x = val / 2; // Start in the middle
int y = val / 2; // Start in the middle
StackX.push(x);
StackY.push(y);
while (!StackX.isEmpty()) {
Array[x][y] = true; // is Visited
x = StackX.peek();
y = StackY.peek();
if (Array[x][y + 1] == false) {
StackX.push(x);
StackY.push(y + 1);
y = y + 1;
} else if (Array[x][y - 1] == false) {
StackX.push(x);
StackY.push(y - 1);
y = y - 1;
} else if (Array[x + 1][y] == false) {
StackX.push(x + 1);
StackY.push(y);
x = x + 1;
} else if (Array[x - 1][y] == false) {
StackX.push(x - 1);
StackY.push(y);
x = x - 1;
} else {
StackX.pop();
StackY.pop();
}
convertArray(Array, val); // add this line
}
}
The solution is still the same as when you last posted this question - you need to have two arrays
-one that is true for every place in the maze that is a wall - the maze's tiles
-one that starts all false - the solver's tiles
The solver can move onto a tile only if both arrays are false at that point, and sets the second array (the solver's tiles) to true while leaving the first array (the maze's tiles) alone.
This is not a 'coding' bug, per say. You simply don't know what behavior you want. Try commenting out the line where you generate the maze. Run your program with 6 as a parameter. You get:
* * * * * *
* *
* *
* *
* *
* * * * * *
What kind of maze is this? Where is the exit? Again, this is not a coding issue, this is a design flaw. Of course if you start within the bounds of this maze, you will visit all of the squares!
I'm not clear what do you expect in your output exactly, but I can see where the issue is. In your generateMaze() method you are travelling like in spiral mode which ends up touching each and every node in the end. Like suppose you have 5x5 array, you travel and make true like (boundaries are already true) [2,2]->[2,3]->[3,3]->[3,2]->[3,1]->[2,1]->[1,1]->[1,2]->[1,3]
you start from middle, you start visiting and take turns just before you find already true (boundary or visited), and it covers all the nodes

Categories