Given a 2D array, find out if a given node is surrounded

Given a 2D array where each digit represents a different color, I want to be able to find out if a given node in the array is surrounded completely by one color. For example, in the 2d array below, I want to be able to confirm that the node at [3][3] is completely surrounded by the color represented by "1". Is there an existing common algorithm that accomplishes this?

{{1, 1, 1, 1, 1, 1, 1, 1},
 {1, 1, 1, 1, 1, 1, 0, 0},
 {1, 1, 1, 1, 1, 1, 1, 1},
 {1, 2, 2, 2, 2, 1, 1, 0},
 {1, 1, 1, 2, 2, 1, 1, 1},
 {1, 1, 1, 2, 2, 2, 2, 1},
 {1, 1, 1, 1, 1, 2, 1, 1},
 {1, 1, 1, 1, 1, 1, 2, 1}}

EDIT: Sorry I am not asking about whether the target node is immediately surrounded. I am asking about whether if you move out from the target node, you can reach the edge of the array without crossing over the boundary color.

My current code is the following, but it's not quite working


let squaresChecked = []
let squareSurrounded = true
let boardSize = 15
let gameBoard = new Array(boardSize)
for(let i=0; i<gameBoard.length; i++){
 gameBoard[i] = Array(boardSize).fill('white')
}


checkSurrounded(x, y, boundaryColor){
    if(x >= boardSize || y >= boardSize || x < 0 || y < 0){
      squareSurrounded = false
      return
    }
    if(gameBoard[x][y] === boundaryColor){return}
    if(squaresChecked.includes(x + ' ' + y)){return}
    squaresChecked.push(x + ' ' + y)

    checkSurrounded(x+1, y, boundaryColor)
    checkSurrounded(x-1, y, boundaryColor)
    checkSurrounded(x, y+1, boundaryColor)
    checkSurrounded(x, y-1, boundaryColor)
}

1 answer

  • answered 2021-10-24 17:43 Sahil Jain

    This should check for top, left, right, bottom for given cell at row,col in 2D array if surrounded by var surroundedBy (1).

    row = 2
    col = 2
    arr = [[1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 0, 0],
           [1, 1, 1, 1, 1, 1, 1, 1],
           [1, 2, 2, 2, 2, 1, 1, 0],
           [1, 1, 1, 2, 2, 1, 1, 1],
           [1, 1, 1, 2, 2, 2, 2, 1],
           [1, 1, 1, 1, 1, 2, 1, 1],
           [1, 1, 1, 1, 1, 1, 2, 1]]
    surroundedBy = 1
    if(arr[row-1][col] ===surroundedBy && arr[row+1][col] === surroundedBy && arr[row][col - 1] === surroundedBy && arr[row][col + 1] === surroundedBy) {
         console.log('surrounded');
    }else{
          console.log('not surrounded');
    }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum