Recursion Showing Adjacent Blank Mines in Minesweeper - java

I am fairly new to Java and I have been working on a Minesweeper game. I am trying to get the adjacent cells to be revealed recursively when an empty cell is clicked. I do this by calling showCell() shown below:
Cells array declaration and population:
private final Cell[][] cells;
public void newGame()
{
numMinesLeft = NUM_MINES;
numCellsLeft = NUM_ROWS * NUM_COLS;
hasHitMine = false;
Cell[] newCells = new Cell[NUM_ROWS * NUM_COLS];
int k = 0; // index in newCells
// create the cells with the mines
while (k < NUM_MINES && k < newCells.length)
{
newCells[k] = new Cell(MINE);
k++;
}
// create the cells without the mines
while (k < newCells.length)
{
newCells[k] = new Cell();
k++;
}
// uniformly mix newCells
for (k = newCells.length; k > 1;)
{
int r = generator.nextInt(k);
k--;
// interchange newCells[r] and newCells[k]
Cell temp = newCells[k];
newCells[k] = newCells[r];
newCells[r] = temp;
}
k = 0;
// place cells into the cells array
for (int i = 0; i < NUM_ROWS; ++i)
{
for (int j = 0; j < NUM_COLS; ++j)
{
cells[i][j] = newCells[k];
k++;
}
}
for(int i = 0; i<NUM_ROWS; i++)
{
for (int j = 0; j<NUM_COLS; j++)
{
int numOfBorderMines = 0;
if (cells[i][j].value != MINE)
{
if(isInTheGrid(i-1, j) == true)
{
if (cells[i-1][j].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i+1, j) == true)
{
if (cells[i+1][j].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i, j - 1) == true)
{
if (cells[i][j - 1].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i, j + 1) == true)
{
if (cells[i][j + 1].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i - 1, j + 1) == true)
{
if (cells[i - 1][j + 1].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i + 1, j - 1) == true)
{
if (cells[i + 1][j - 1].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i + 1, j + 1) == true)
{
if (cells[i + 1][j + 1].value == MINE )
{
numOfBorderMines++;
}
}
if(isInTheGrid(i - 1, j - 1) == true)
{
if (cells[i - 1][j - 1].value == MINE )
{
numOfBorderMines++;
}
}
cells[i][j].value = numOfBorderMines;
}
}
}
}
toggleFlag()
public void toggleFlag(int row, int col)
{
if (isCellShowing(row, col) || isOver()) return;
if (isCellFlagged(row, col))
{
// unflag cell
cells[row][col].hasFlag = false;
numMinesLeft++;
numCellsLeft++;
}
else if (numMinesLeft > 0)
{
// flag cell
cells[row][col].hasFlag = true;
numMinesLeft--;
numCellsLeft--;
}
ui.updateCell(row, col);
}
showCell()
public void showCell(int row, int col)
{
// checks is cell has been flagged or if the game is over, otherwise it reveals the cell
if(isCellFlagged(row, col) == true || isOver())
{
return;
}
else
{
cells[row][col].isShowing = true;
ui.updateCell(row, col);
}
// checks if cell has a mine and triggers hasHitMine otherwise subtracts 1 from class variable numCellsLeft
if (cells[row][col].value == MINE)
{
hasHitMine = true;
}
else
{
numCellsLeft--;
}
// if there are no mines adjacent, recursively reveal the adjacent cells
if(cells[row][col].value == 0)
{
showCell(row + 1, col);
showCell(row - 1, col);
showCell(row, col + 1);
showCell(row, col -1);
showCell(row + 1, col - 1);
showCell(row + 1, col + 1);
showCell(row - 1, col - 1);
showCell(row - 1, col + 1);
}
}
The problem I am having is when I hit this portion of the code and click an empty cell, it reveals all cells adjacent continuously down a column or a row in one direction. I can't get my implementation of recursion right, perhaps I am approaching it wrong. My idea was to reveal each adjacent cell according to the grid position.

I solved my problem by implementing Tail Recursion. Here is my updated showCell() method and tail recursion method:
public void showCell(int row, int col)
{
// checks is cell has been flagged or if the game is over, otherwise it reveals the cell
if(isCellFlagged(row, col) == true || isOver())
{
return;
}
else
{
cells[row][col].isShowing = true;
ui.updateCell(row, col);
}
// checks if cell has a mine and triggers hasHitMine otherwise subtracts 1 from class variable numCellsLeft
if (cells[row][col].value == MINE)
{
hasHitMine = true;
}
else
{
numCellsLeft--;
}
// if there are no mines adjacent, recursively reveal the adjacent cells
if(cells[row][col].value == 0)
{
if(isInTheGrid(row - 1, col) == true)
{
showCell(row - 1, col, cells[row - 1][col].isShowing);
}
if(isInTheGrid(row + 1, col) == true)
{
showCell(row + 1, col, cells[row + 1][col].isShowing);
}
if(isInTheGrid(row, col - 1) == true)
{
showCell(row, col - 1, cells[row][col - 1].isShowing);
}
if(isInTheGrid(row, col + 1) == true)
{
showCell(row, col + 1, cells[row][col + 1].isShowing);
}
if(isInTheGrid(row + 1, col - 1) == true)
{
showCell(row + 1, col - 1, cells[row + 1][col - 1].isShowing);
}
if(isInTheGrid(row - 1, col + 1) == true)
{
showCell(row - 1, col + 1, cells[row - 1][col + 1].isShowing);
}
if(isInTheGrid(row + 1, col + 1) == true)
{
showCell(row + 1, col + 1, cells[row + 1][col + 1].isShowing);
}
if(isInTheGrid(row - 1, col - 1) == true)
{
showCell(row - 1, col - 1, cells[row - 1][col - 1].isShowing);
}
}
else
{
return;
}
}
public boolean isInTheGrid(int x, int y)
{
if (x < 0 || y < 0) return false;
if(x >= NUM_ROWS || y >= NUM_COLS) return false;
return true;
}
public void showCell(int row, int col, boolean isShown)
{
if (isShown != true)
{
cells[row][col].isShowing = true;
ui.updateCell(row, col);
}
else
{
return;
}
}

When you call show cell for surrounding cells, you want to make sure that you don't re-show the cell you called it from, or past cells that were shown from the previous calls in the recursion stack.
If I understood your question correctly, I believe you are referring the case in Minesweeper where if you click on an empty cell, then it will reveal the adjacent empty cells.

Related

Recursive Function to find regions in matrix

Given a NxN matrix (which contains Boolean values - true / false).
We will define:
true region in an array as a maximum collection of adjacent cells that all have a true value.
Cells located diagonally to each other are not considered adjacent.
In this example, there are 3 true areas:
True Regions
My Solution attemp in Java:
public static int (boolean[][] mat) {
return GetTrueRegions(mat, 0, 0);
}
public static int GetTrueRegions(boolean[][] m, int i , int j) {
final boolean VISITED = false;
if (i == m.length - 1 && j == m[0].length - 1)
return 0;
// avoid repeat a cell
boolean temp = m[i][j];
m[i][j] = VISITED;
// recursion for all neighbors
int up = -1, down = -1, left = -1, right = -1;
if (i - 1 >= 0 && m[i-1][j] )
up = GetTrueRegions(m, i - 1, j);
if (i + 1 < m.length && m[i+1][j])
down = GetTrueRegions(m, i + 1, j);
if (j - 1 >= 0 && m[i][j-1])
left = GetTrueRegions(m, i, j - 1);
if (j + 1 < m[0].length && m[i][j+1] )
right = GetTrueRegions(m, i, j + 1);
// couldn't find a path
if (temp) {
return 1 + GetTrueRegions(m, i, j + 1);
}
if (up == -1 && down == -1 && left == -1 && right == -1 )
return GetTrueRegions(m, i, j +1);
return up + down + left + right;
}
this obviously not working.
I was thinking about going through each cell, and if the cell has true value, adding 1 to the total regions(somehow), and put the value false to him and to each adjacent cell(mark the region as "visited").
though I find it hard for me to get the base cases, and how to get every region value.
try to look at something like that:
public static int GetTrueRegions(boolean[][] mat)
{
return GetTrueRegions(mat, 0, 0);
}
private static int GetTrueRegions(boolean[][] m, int i, int j)
{
if (j == m[0].length)
return 0;
if (i == m.length)
return GetTrueRegions(m, 0, j + 1);
// found a region
if (m[i][j])
{
// mark the entire region, to avoid duplications
markRegionAsFalse(m, i, j);
// count 1 region and proceed
return 1 + GetTrueRegions(m, i + 1, j);
}
// proceed...
return GetTrueRegions(m, i + 1, j);
}
private static void markRegionAsFalse(boolean[][] matrix, int row, int col)
{
// just visited...
matrix[row][col] = false;
if(row - 1 >= 0 && matrix[row - 1][col]) // move up and mark cell if true
markRegionAsFalse(matrix, row - 1, col);
if (row < matrix.length - 1 && matrix[row + 1][col]) // move down and mark cell if true
markRegionAsFalse(matrix, row + 1, col);
if (col < matrix.length - 1 && matrix[row][col + 1]) // move right and mark cell if true
markRegionAsFalse(matrix, row, col + 1);
if(col - 1 >= 0 && matrix[row][col - 1]) // move left and mark cell if true
markRegionAsFalse(matrix, row, col - 1);
}

Trying to check everything adjacent in Matrix

I was wondering if there was a more simple way to do this? The project requires me to write this method that uses another method that returns a Boolean of true or false if there is treasure located there. I got that method down, but it now wants me to write a method that returns how much treasure is located adjacent (in all directions) to a set place in a row and column. I mapped this out on a piece of paper and came out with... this. But, I feel like I am repeating code but I don't understand any other way that can satisfy the condition. I would love for it to be more condensed... I was thinking 2 for loops? But there's two conditions that wouldn't work in the for loop.
//precondition: 0<=row<rows in map and 0<=col<cols in map
//postcondition: returns a count of the number of treasures in the cells adjacent to the location row,col
//horizontally, vertically, and diagonally.
public int numAdjacent(int row, int col) {
if(hasTreasure(row,col)) {
return -1;
}
int numOfTreasure = 0;
if ((0<=row && row < mapHeight()) && (0<=col && col < mapWidth())) {
if(hasTreasure(row - 1,col - 1)) {
numOfTreasure++;
}
}
if (0<=row && row < mapHeight()) {
if(hasTreasure(row - 1,col)) {
numOfTreasure++;
}
}
if ((0<=row && row < mapHeight()) && 0<=col && col < mapWidth()) {
if(hasTreasure(row - 1,col + 1)) {
numOfTreasure++;
}
}
if (0<=row && row < mapHeight()) {
if(hasTreasure(row + 1,col)) {
numOfTreasure++;
}
}
if ((0<=row && row < mapHeight()) && 0<=col && col < mapWidth()) {
if(hasTreasure(row + 1,col + 1)) {
numOfTreasure++;
}
}
if ((0<=row && row < mapHeight()) && 0<=col && col < mapWidth()) {
if(hasTreasure(row + 1,col - 1)) {
numOfTreasure++;
}
}
if (0<=col && col < mapWidth()) {
if(hasTreasure(row,col + 1)) {
numOfTreasure++;
}
}
if (0<=col && col < mapWidth()) {
if(hasTreasure(row,col - 1)) {
numOfTreasure++;
}
}
return numOfTreasure;
}
You're on the right track with using nested for-loops! Because we're dealing with a matrix, each element has 8 adjacent neighbors at which treasure can be located. For this reason, we can use nested for-loops to check if each adjacent neighbor has treasure; if the neighbor's coordinates are out-of-bounds, we simply skip it within the loop.
public int numAdjacent(int row, int col) {
int numOfTreasure = 0;
for (int currentCol = col - 1; currentCol <= col + 1; currentCol++) {
for (int currentRow = row - 1; currentRow <= row + 1; currentRow++) {
if (currentRow < 0 || currentRow >= mapHeight() || currentCol < 0 || currentCol >= mapWidth()) {
continue;
}
numOfTreasure += hasTreasure(currentRow, currentCol) ? 1 : 0;
}
}
return numOfTreasure;
}
Once you understand that for-loop, it can be simplified even further:
public int numAdjacent(int row, int col) {
int numOfTreasure = 0;
for (int currentCol = Math.max(0, col - 1); currentCol <= Math.min(col + 1, mapWidth() - 1); currentCol++) {
for (int currentRow = Math.max(0, row - 1); currentRow <= Math.min(row + 1, mapHeight() - 1); currentRow++) {
numOfTreasure += hasTreasure(currentRow, currentCol) ? 1 : 0;
}
}
return numOfTreasure;
}

Crossword algorithm for Android using Java [duplicate]

This question already has answers here:
Algorithm to generate a crossword [closed]
(13 answers)
Closed 6 years ago.
I am working on cross word algorithm to develop a word app. After doing a lot of googling or search on StackOverflow, I was able to reach this point. But yet I am not able to understand the right implementation for algorithm in Java. Below is the class I used.
public class Crosswords {
char[][] cross;
int rows;
int cols;
char[][] numberGrid;
boolean startword;
final char DEFAULT = ' ';
public Crosswords() {
rows = 50;
cols = 50;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length;i++){
for (int j = 0; j < cross[i].length;j++){
cross[i][j] = DEFAULT;
}
}
}
public Crosswords(int ros, int colls) {
rows = ros;
cols = colls;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0;i < cross.length; i++){
for (int j = 0; j < cross[i].length; j++){
cross[i][j] = DEFAULT;
}
}
}
public String toString() {
String s = new String();
//String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
s = s + cross[i][j] + " ";
}
s = s + "\n";
}
return s;
}
public void addWordh(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > cols) {
System.out.println(s + " is longer than the grid. Please try another word.");
return;
}
if (c + s.length() > cols) {
System.out.println(s + " is too long. Please try another word.");
return;
}
if ((r - 2) >= 0) {
if ((cross[r - 1][c - 1 + s.length()] == DEFAULT) || (cross[r - 1][c - 1 + s.length()] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the beginning of another word!");
return;
}
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1][c - 1 + i] == DEFAULT) || (cross[r - 1][c - 1 + i] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= cols) && (c + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1][c - 1 + j] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1)][cols - 1 - (c - 1 + j)] = '*';
j++;
}
}
}
}
public void addWordv(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > rows) {
System.out.println(s + " is longer than the grid. Please try another word.");
}
if (r + s.length() > rows) {
System.out.println(s + " is too long. Please try another word.");
}
else {
if ((r - 2) >= 0) {
if ((cross[r - 2][c - 1] == DEFAULT) || (cross[r - 2][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
}
if ((cross[r - 1 + s.length()][c - 1] == DEFAULT) || (cross[r - 1 + s.length()][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1 + i][c - 1] == DEFAULT) || (cross[r - 1 + i][c - 1] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= rows) && (r + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1 + j][c - 1] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1 + j)][cols - 1 - (c - 1)] = '*';
j++;
}
}
}
}
}
public void setNumberGrid(){
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (cross[i][j] == DEFAULT){
numberGrid[i][j] = (char) 0;
}
else if (startword == true){
numberGrid[i][j] = (char) -2;
}
else {
numberGrid[i][j] = (char) -1;
}
}
int count = 1;
for (i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == -2){
numberGrid[i][j] = (char)count;
count++;
}
}
}
}
}
public String printNumberGrid() {
for (int i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == (char)-1){
numberGrid[i][j] = ' ';
}
else if (numberGrid[i][j] == (char)0){
numberGrid[i][j] = '#';
}
}
}
String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
d = d + numberGrid[i][j] + " ";
}
d = d + "\n";
}
return d;
}
public static void main(String[] args) {
Crosswords g = new Crosswords();
g.addWordv("rawr", 4, 5);
g.addWordh("bot", 5, 4);
g.addWordv("raw", 7, 5);
g.addWordh("cat", 4, 5);
g.addWordh("bass", 6, 10);
System.out.println(g);
Crosswords c = new Crosswords(20, 20);
c.addWordh("HELLO", 1, 1);
c.addWordv("HAPLOID", 1, 1);
c.addWordh("COMPUTER", 3, 12);
c.addWordv("CAT", 2, 11);
c.addWordv("WOAH", 2, 20);
c.addWordh("PARKING", 20, 5);
c.addWordv("ARK", 17, 6);
c.addWordh("AHOY", 6, 18);
c.addWordv("AHOY", 18, 10);
c.addWordv("ADVANTAGE", 2, 12);
c.addWordv("INTERNAL", 2, 18);
c.addWordh("BANTER", 7, 11);
c.addWordv("BEAGLE", 5, 12);
c.addWordh("BASE", 8, 3);
c.addWordv("BALL", 8, 3);
c.addWordh("LEFT", 10, 3);
c.addWordv("SAFE", 8, 5);
System.out.print(c);
}
}
As you can see in Main method that i am adding the words but also giving the row and column number to place the words like c.addWordv("Safe",8,5); where 8 and 5 is column number.
Now Question is how can i implement cross word algorithm which just take words and place them on board randomly without taking the row and column numbers.
Thanks in advance
EDIT:
I want to modify this class algo the way that i dont have to give away the rows and columns number..
//Pseudo Code
If the crossword size is maxSize and any word's length is stored in wordLength ,then you can use random method as below
int maxSize=20;
int wordLength=4;
Random random =new Random();
int r,c;
//for horizontal
r=random.nextInt(maxSize-wordLength);
c=random.nextInt(maxSize);
//for vertical
r=random.nextInt(maxSize);
c=random.nextInt(maxSize-wordLength);
You can store the row and column and generate the new one if its already present.

How do I deal with out of bounds for Conway's Game of Life?

Currently working on a class project trying to recreate Conway's Game of Life. Here's a copy of my code, my main issue is with my runRound() method. I have to go through and check to see how many neighbors each cell has that are alive(true) or dead(false) and edit my new grid accordingly. However I keep going out of bounds when trying to check around the edges of my grid and tried to implement code to avoid that but I must be missing something. Thank for any advice! still kind of new to this!
package Programs;
public class GameOfLife {
private boolean[][] grid;
private int time;
public GameOfLife() {
grid = new boolean[10][10];
time = 0;
}
public GameOfLife(int row, int col) {
if (row < 1) {
row = 10;
}
if (col < 1) {
col = 10;
}
grid = new boolean[row][col];
time = 0;
}
public boolean[][] getGrid() {
boolean[][] newGrid = new boolean[grid.length][grid[1].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
newGrid[i][j] = grid[i][j];
}
}
return newGrid;
}
public int getTime() {
return time;
}
public void simpleSetUp(int[][] array) {
if (getTime() == 0) {
for (int row = 0; row < array.length; row++) {
if (array[0].length == 2) {
if (array[row][0] >= 0 && array[row][1] >= 0 && array[row][0] <= grid[0].length
&& array[row][1] <= grid[0].length) {
grid[array[row][0]][array[row][1]] = true;
}
}
}
}
}
public void clearGrid() {
this.time = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; row < grid[col].length; col++) {
grid[row][col] = false;
}
}
}
public void runRound() {
time++;
int live;
boolean[][] newGrid = getGrid();
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[col].length; col++) {
live = 0;
if (row - 1 >= 0 || col - 1 >= 0) {
if(grid[row - 1][col - 1] == true){
live++;
}
}
if (row + 1 < grid.length || col + 1 < grid[col].length) {
if(grid[row + 1][col + 1] == true){
live++;
}
}
if (row - 1 >= 0 || col + 1 < grid[col].length) {
if(grid[row - 1][col + 1] == true ){
live++;
}
}
if (row + 1 < grid.length || col - 1 >= 0) {
if(grid[row + 1][col - 1] == true){
live++;
}
}
if (row + 1 < grid.length) {
if(grid[row + 1][col] == true){
live++;
}
}
if (row - 1 >= 0) {
if(grid[row - 1][col] == true){
live++;
}
}
if (col + 1 < grid[col].length) {
if(grid[row][col + 1] == true){
live++;
}
}
if (col - 1 >= 0) {
if(grid[row][col - 1] == true){
live++;
}
}
if (grid[row][col] == true && live == 2 || live == 3) {
newGrid[row][col] = true;
} else {
newGrid[row][col] = false;
}
}
}
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[col].length; col++) {
live = 0;
if (row - 1 >= 0 || col - 1 >= 0) {
if(grid[row - 1][col - 1] == false){
live++;
}
}
if (row + 1 < grid.length || col + 1 < grid[col].length) {
if(grid[row + 1][col + 1] == false){
live++;
}
}
if (row - 1 >= 0 || col + 1 < grid[col].length) {
if(grid[row - 1][col + 1] == false){
live++;
}
}
if (row + 1 < grid.length || col - 1 >= 0) {
if(grid[row + 1][col - 1] == false ){
live++;
}
}
if (row + 1 < grid.length) {
if(grid[row + 1][col] == false ){
live++;
}
}
if (row - 1 >= 0) {
if(grid[row - 1][col] == false){
live++;
}
}
if (col + 1 < grid[col].length) {
if(grid[row][col + 1] == false){
live++;
}
}
if (col - 1 >= 0) {
if(grid[row][col - 1] == false){
live++;
}
}
if (live == 3) {
newGrid[row][col] = true;
} else {
newGrid[row][col] = false;
}
}
}
}
public void runGame(int foo) {
for (int poo = 0; poo < foo; poo++) {
runRound();
}
}
}
The main problem you have is that your bounds checks are "or" logic: you go ahead with the computation if either row or col is in bounds. You need to have them both in bounds; use an and.
If you're tired of that, you can get a similar effect by padding your entire grid with false values, one layer on each side. Your actual cells are in the range 1 through grid.length+1; row/col 0 and grid.length+2 are false.

java grid boundary

The problem is to find the shortest path on a grid from a start point to a finish point. the grid is a 2 dimensional array filled with 0's and 1's. 1's are the path. I have a method that checks the neighbors of a given coordinate to see if its a path. The problem im having is with the boundaries of the grid. The right and bottom boundary can just be checked using the arrays length and the length of a column. But how would i check to make sure that i dont try to check a point thats to the left of the grid or above the grid?
This is my method
public static void neighbors(coordinate current, int[][] grid, Queue q)
{
int row = current.getRow();
int col = current.getCol();
if(grid[row-1][col] == 1)
{
if(grid[row][col] == -1)
{
grid[row-1][col] = grid[row][col] + 2;
}
else
{
grid[row-1][col] = grid[row][col] + 1;
}
coordinate x = new coordinate(row-1,col);
q.enqueue(x);
}
else if(grid[row+1][col] == 1)
{
if(grid[row][col] == -1)
{
grid[row+1][col] = grid[row][col] + 2;
}
else
{
grid[row+1][col] = grid[row][col] + 1;
}
coordinate x = new coordinate(row+1,col);
q.enqueue(x);
}
else if(grid[row][col-1] == 1)
{
if(grid[row][col] == -1)
{
grid[row][col-1] = grid[row][col] + 2;
}
else
{
grid[row][col-1] = grid[row][col] + 1;
}
coordinate x = new coordinate(row, col - 1);
q.enqueue(x);
}
else if(grid[row][col+1] == 1)
{
if(grid[row][col+1] == -1)
{
grid[row][col+1] = grid[row][col] + 1;
}
else
{
grid[row][col+1] = grid[row][col] + 1;
}
coordinate x = new coordinate(row, col + 1);
q.enqueue(x);
}
else
{
}
q.dequeue();
}
I assume that the leftmost and topmost indexes are 0 in your arrays, so just make sure that index-1 >= 0 before indexing into the appropriate array.

Categories

Resources