Find inside of rectangle using outside points - java

I have a csv file with numbers(i.e. 0, 2, 34, 0, 2,...) all on one line. I am using a scanner to read them from a file. The file represents an in-game map which is quite large. I know the width and height of this map. While scanning this file, I only want to capture the brown rectangle(part of the game's map) in the image below. I am scanning the file and wanting to put the values from the csv file into a short[].
int mapWidth = 8;
int mapHeight = 6;
int rectangleWidth = 5;
int rectangleHeight = 3;
short[] tmpMap = new short[rectangleWidth * rectangleHeight];
Scanner scanner = new Scanner(new File(path));
scanner.useDelimiter(", ");
I also am lucky enough to know the 4 corners of the rectangle that I need. The dark brown squares(four corners of the rectangle I need to capture) can be represented as:
int topLeftIndex = 17;
int topRightIndex = 21;
int bottomLeftIndex = 33;
int bottomRightIndex = 37;
I know that during my scan method I can check to see if I am within bounds of the rectangle and the blue highlighted boxes with the following:
if (count >= topLeftIndex && count <= bottomRightIndex){
//within or outside (east and west) of rectangle
I am having trouble thinking of the logic for identifying and not storing the blue highlighted squares.
The size of this rectangle, size of the overall map, and dark brown point are just numeric examples and will change, but I will always know them. Can anyone help me out?
Here is what I have so far:
private static short[] scanMapFile(String path, int topLeftIndex,
int topRightIndex, int bottomLeftIndex, int bottomRightIndex)
throws FileNotFoundException {
Scanner scanner = new Scanner(new File(path));
scanner.useDelimiter(", ");
short[] tmpMap = new short[mapWidth * mapHeight];
int count = 0;
int arrayIndex = 0;
while(scanner.hasNext()){
if (count >= topLeftIndex && count <= bottomRightIndex){
//within or outside (east and west) of rectangle
if (count == bottomRightIndex){ //last entry
tmpMap[arrayIndex] = Short.parseShort(scanner.next());
break;
} else { //not last entry
tmpMap[arrayIndex] = Short.parseShort(scanner.next());
arrayIndex++;
}
} else {
scanner.next(); //have to advance scanner
}
count++;
}
scanner.close();
return tmpMap;
}
NOTE: this is not school work :) Any help would be tremendously appreciated.

You could to it like this:
public boolean isInside(int n) {
if(n >= topLeftIndex && n <= bottomRightIndex) {
if(n % mapWidth >= topLeftIndex % mapWidth
&& mapWidth % mapWidth <= bottomRightIndex % mapWidth) {
return true;
}
}
return false;
}
This first checks, what you have already checked and then checks, whether the "column" is right as well.
This works always if you know the top-left index, the bottom-right index, and the map width.

Here is what I did to capture all of the sides:
int topLeftChunkIndex = characterX - (chunkWidth / 2) + ((characterY - (chunkHeight / 2)) * mapWidth);
int topRightChunkIndex = topLeftChunkIndex + chunkWidth - 1;
//int bottomRightChunkIndex = characterX + (chunkWidth / 2) + ((characterY + (chunkHeight / 2)) * mapWidth);
//int bottomLeftChunkIndex = bottomRightChunkIndex - chunkWidth + 1;
int[] leftChunkSides = new int[chunkHeight];
int[] rightChunkSides = new int[chunkHeight];
for (int i = 0; i < chunkHeight; i++){
leftChunkSides[i] = topLeftChunkIndex + (mapWidth * i);
rightChunkSides[i] = topRightChunkIndex + (mapWidth * i);
}
And here is how I checked later:
public static boolean isInsideMapChunk(int n, int[] leftChunkSides, int[] rightChunkSides) {
for (int i = 0; i < chunkHeight; i++){
if (n >= leftChunkSides[i] && n <= rightChunkSides[i]){
return true;
}
}
return false;
}

Related

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...

search a given word into a letter puzzle diagonally

I have a two-dimensional array filled with random letters. I have words to find in that array.
I have written a toString method that uses:
startX : The start X position of the String to be found
startY : The start Y position of the String to be found
endX : The end X position of the String to be found
endY : The end Y position of the String to be found
The code that I provide works horizontally and vertically but does not work for diagonals. How can I print words which are placed in the array diagonally?
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (startX == endX) {
if (startY < endY) {
for (int i = startY; i <= endY; i++)
sb.append(i).append("x").append(startY).append(" ");
} else {
for (int i = endY; i <= startY; i++)
sb.append(i).append("x").append(startY).append(" ");
}
}
if (startY == endY) {
if (startX < endX) {
for (int i = startX; i <= endX; i++)
sb.append(i).append("x").append(startY).append(" ");
} else
for (int i = endX; i <= startX; i++)
sb.append(i).append("x").append(startY).append(" ");
}
if (startX > endX && startY > endY) {
int i = startX;
int j = startY;
while (i >= endX)
sb.append(i--).append("x").append(j--).append(" ");
} else if (startX > endX && startY < endY) {
int i = startX;
int j = startY;
while (i >= endX)
sb.append(i--).append("x").append(j++).append(" ");
} else if (startX < endX && startY > endY) {
int i = startX;
int j = startY;
while (i >= endX)
sb.append(i++).append("x").append(j--).append(" ");
} else if (startX < endX && startY < endY) {
int i = startX;
int j = startY;
while (i >= endX)
sb.append(i++).append("x").append(j++).append(" ");
}
return sb.toString();
}
I assume that what you are looking for is a way to find a word in a letter puzzle.
In such a case, I suggest you to store the puzzle on a 2D array and the word to find in a String. Then you need to check all the positions of the array that have the same character than the begining character of the String you are looking for (in the code I provide: findWord). Once you find a match, you need to check the rest of the characters of the string (in the code I provide: checkDirections). If the rest of the characters match then you have found the string, otherwise you need to check for the other directions or for the next appearance of the first letter of the string.
Next I provide the code:
package letterPuzzle;
import java.util.Random;
public class LetterPuzzle {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private static final int[] DIRECTIONS_X = new int[] { 0, 0, 1, -1, 1, 1, -1, -1 };
private static final int[] DIRECTIONS_Y = new int[] { 1, -1, 0, 0, 1, -1, 1, -1 };
private static int N;
private static char[][] puzzle;
private static void initializePuzzle() {
Random r = new Random();
puzzle = new char[N][N];
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
puzzle[i][j] = ALPHABET.charAt(r.nextInt(ALPHABET.length()));
}
}
// Add the JAVA word in a location
if (N < 6) {
System.out.println("[ERRRO] Example needs N >= 6");
System.exit(1);
}
puzzle[2][3] = 'j';
puzzle[3][3] = 'a';
puzzle[4][3] = 'v';
puzzle[5][3] = 'a';
}
private static void printPuzzle() {
System.out.println("[DEBUG] Puzzle");
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
System.out.print(puzzle[i][j] + " ");
}
System.out.println("");
}
System.out.println("[DEBUG] End Puzzle");
}
private static boolean findWord(String word) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
// We check all the matrix but only try to match the word if the first letter matches
if (puzzle[i][j] == word.charAt(0)) {
if (checkDirections(i, j, word)) {
return true;
}
}
}
}
return false;
}
private static boolean checkDirections(int initX, int initY, String word) {
System.out.println("Searching " + word + " from (" + initX + ", " + initY + ")");
// Checks the different directions from (initX, initY) position
for (int dirIndex = 0; dirIndex < DIRECTIONS_X.length; ++dirIndex) {
System.out.println(" - Searching direction " + dirIndex);
boolean wordMatches = true;
// Checks all the characters in an specific direction
for (int charIndex = 0; charIndex < word.length() && wordMatches; ++charIndex) {
int x = initX + DIRECTIONS_X[dirIndex] * charIndex;
int y = initY + DIRECTIONS_Y[dirIndex] * charIndex;
System.out.println(" -- Checking position (" + x + ", " + y + ")");
if (x < 0 || y < 0 || x >= N || y >= N || puzzle[x][y] != word.charAt(charIndex)) {
System.out.println(" -- Not match");
wordMatches = false;
} else {
System.out.println(" -- Partial match");
}
}
// If the word matches we stop, otherwise we check other directions
if (wordMatches) {
return true;
}
}
return false;
}
public static void main(String[] args) {
// Check args
if (args.length != 2) {
System.err.println("[ERROR] Invalid usage");
System.err.println("[ERROR] main <puzzleSize> <wordToSearch>");
}
// Get args
N = Integer.valueOf(args[0]);
String word = args[1];
// Initialize puzzle (randomly)
initializePuzzle();
printPuzzle();
// Search word
boolean isPresent = findWord(word);
if (isPresent) {
System.out.println("Word found");
} else {
System.out.println("Word NOT found");
}
}
}
Notice that:
The puzzle matrix is randomly initialized and I hardcoded the word 'java' on the 2,3 -> 5,3 positions (this is just for the example but you should initialize the puzzle from the command line or from a file).
The ALPHABET variable is used only for the random generation.
The directions are stored on two 1D arrays to make the 8 directions programatically but you can unroll for the sake of clarity.
It is probably not best efficient code in terms of performance since you will double check lots of positions if the first character of the string appears several times. However it is still a feasible and easy solution.
If :
each word of yours is in a particular row and doesn't overflows to next row and
all words are consecutive
then you can do something like this:
#Override
public String toString()
{
StringBuilder string = new StringBuilder();
for(int c = startY; c<=endY; c++) {
string.append(startX).append("x").append(c).append(", ");
}
return string.toString();
}

How to create a Battleship Warship game algorithm

I'm having trouble randomizing and adding a 2x2 ship into the game board. I need it to look like the following:
currently I can only seem to get a 1x1 ship and don't quite understand the logic for adding the 2x2 and randomizing it so that they're all connected.
also when the user inputs a '2' at the main menu I need to show the solution, meaning where the ships are. Which I also could use some help on.
Not nearly finished but please be critical when it comes to judging my code, everything helps!
Thanks in advance.
import java.util.Scanner;
public class Battleship
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int [][] board = new int [5][5];
int [][] ship = new int [4][2];
int [] shot = new int[2];
boolean done = false;
resetboard(board);
while(!done)
{
displayBoard(board);
displayMenu();
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
int choice = getMenuInput(input);
if(choice == 1)
{
getRow(shot);
getColumn(shot);
if(fireShot(shot,ship) == true)
{
board[shot[0]][shot[1]]= 1;
}
else
{
board[shot[0]][shot[1]]= 0;
}
}
else if(choice == 2)
{
for (int x = 0; x < 5; x++)
{
for(int y = 0; y < 5; y++)
{
for(int z = 0; z < 3; z++)
{
if(board[x][y] == ship[z][0] && board[x][y] == ship[z][1] )
{
board[ship[z][0]][ship[z][1]]= 1;
}
}
}
}
displayBoard(board);
}
else if (choice == 3)
{
done = true;
System.out.println("Thanks For Playing");
}
}
}
public static void displayBoard(int [][] board)
{
System.out.println(" A B C D E");
for(int r =0; r < 5; r++)
{
System.out.print((r + 1) + "");
for(int c = 0; c < 5; c++)
{
if(board[r][c] == -1)
{
System.out.print(" -");
}
else if(board[r][c] == 0)
{
System.out.print(" X");
}
else if(board[r][c] == 1)
{
System.out.print(" *");
}
}
System.out.println("");
}
}
public static void resetboard(int[][] a)
{
for(int row=0 ; row < 5 ; row++ )
{
for(int column=0 ; column < 5 ; column++ )
{
a[row][column]=-1;
}
}
}
public static void displayMenu()
{
System.out.println("\nMenu:");
System.out.println("1. Fire Shot");
System.out.println("2. Show Solution");
System.out.println("3. Quit");
}
public static int getMenuInput(Scanner input)
{
int in = 0;
if(input.hasNextInt())
{
in = input.nextInt();
if(in>0 && in<4)
{
in = in;
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("Invalid Entry, Please Try Again.\n");
input.nextInt();
}
return in;
}
public static void getRow(int [] shot)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a Row Number: ");
shot[0] = shotValid(input);
shot[0]--;
}
public static void getColumn(int [] shot)
{
Scanner input = new Scanner(System.in);
int numb = 0;
System.out.println("Enter a Column Letter: ");
String choice = input.next();
if (choice.equals("A"))
{
numb = 0;
}
else if(choice.equals("B"))
{
numb = 1;
}
else if( choice.equals("C"))
{
numb = 2;
}
else if(choice.equals("D"))
{
numb = 3;
}
else if(choice.equals("E"))
{
numb = 4;
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
input.nextLine();
}
shot[1] = numb;
}
public static boolean fireShot(int [] shot, int [][]ship)
{
boolean result = false;
for(int shipHit=0 ; shipHit<ship.length ; shipHit++)
{
if( shot[0]==ship[shipHit][0] && shot[1]==ship[shipHit][1])
{
result = true;
}else
{
result = false;
}
}
return result;
}
public static int shotValid(Scanner quantity)
{
int shot = 0;
boolean done = false;
while(!done)
{
if(quantity.hasNextInt())
{
shot = quantity.nextInt();
if(shot>0 && shot<6)
{
shot = shot;
done = true;
}
else
{
System.out.println("1Invalid Entry, Please Try Again.\n");
}
}
else
{
System.out.println("2Invalid Entry, Please Try Again.\n");
quantity.next();
}
}
return shot;
}
}
You want to place a single ship of size 2×2 on the board and do this:
for(int ships=0 ; ships < 4 ; ships++)
{
ship[ships][0]=(int) Math.random() * 5 + 1;
ship[ships][1]=(int) Math.random() * 5 + 1;
}
There are several errors here:
The random variables will always be 1, because the (int) conversion affects only the result of Math.random(), which is a pseudo-random floating-point number between 0 and 1 exclusively. Conversion to int truncates this to 0. Use (int) (Math.Random() * 5), which will yield a random number from 0 to 4.
You shouldn't add 1. Internally, your game uses the zero-base indices that Java uses, which is good. ()These are known to the outside as rows 1 to 5 ande columns A to E, but you take care of that in your getRow and getColumn functions.)
You place up to four independent ships of size 1×1. (This is up to four, because you might end up wit one ship in an already occupied place.)
To place a single 2×2 ship, just determine the top left corner randomply and make the other ship coordinates dependent on that:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
ship[0][0] = x;
ship[0][1] = y;
ship[1][0] = x + 1;
ship[1][1] = y;
ship[2][0] = x;
ship[2][1] = y + 1;
ship[3][0] = x + 1;
ship[3][1] = y + 1;
You now have two separate data structures: The board, which is all minus ones initially, and the list of ships. Your display routine suggests that you want three different values for a cell in the board: −1 is water; 1 is an unarmed part of a ship and 0 is where a shot has been fired.
But you never set these values. You set the position of the ship before displaying, but you should probably set them straight away. You should also set the locations of shots, so that you never fire at the same cell.
You need two modes for displaying the board: The in-play mode, where the unharmed ships are displayed as water and the solution mode, which shows everything as it is. You could so this by passing a flag to the routine.
Now if you think about it, you don't really need the ship array. Just use the information in the board:
int x = (Math.random() * 4);
int y = (Math.random() * 4);
board[x][y] = 1;
board[x + 1][y] = 1;
board[x][y + 1] = 1;
board[x + 1][y + 1] = 1;
Keep a count of ships, initially 4. When you fire at water, mark the cell with 0. When you fire at a ship, mark the cell as 0 and decrement the count of ships. If the count of ships is zero, the player has won. Otherwise, redisplay the boatrd and shoot again.

inserting an x in between a predrawn base

I want to initialize an x between the first | | and move it as users input left, right, down, up. I think I just mostly need help with putting the x there in the first place. Can probably figure out the rest based on the answer.
public class dimensions {
public static void main(String[] args) {
System.out.println("Select the size of the world widthxheight: ");
Scanner sc = new Scanner(System. in );
String input = sc.nextLine();
String[] parts = input.split("x");
String part1 = parts[0];
String part2 = parts[1];
int sx = 1;
int sy = 0;
int width = Integer.parseInt(part1);
int height = Integer.parseInt(part2);
for (int h = height - 1; h >= 0; h--) {
for (int w = width - 1; w >= 0; w--) {
if (w == width - 1) {
System.out.print("| |");
} else {
System.out.print(" |");
}
}
System.out.print("\n");
}
}
}
You can add an X in the first field with the following code:
[...]
int width = Integer.parseInt(part1);
int height = Integer.parseInt(part2);
int playerPosX = 0;
int playerPosY = 0;
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
String temp = " |";
if (w == 0) {
temp = "| |";
}
if (playerPosX == w && playerPosY == h) {
temp = temp.replace(' ', 'X');
}
System.out.print(temp);
}
System.out.println();
}
}
}
You can also specify the position of the player, respectively the position of the X with the variables playerPosX and playerPosY.
BUT, moving the player without drawing the whole map after each move is not possible, because System.out is technically a stream and it's not possible to manipulate data which was already sent to the stream.
I would suggest that you create your own window in which you add a text field and print the map on that.
Tutorial for creating Swing windows.
Tutorial for creating text areas.

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