Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

convert javascript to java

const testMatrix = [
  [1, 1, 1, 0, 0],
  [1, 1, 1, 0, 1],
  [0, 1, 0, 0, 1],
  [0, 0, 0, 1, 1]
];

const directions = [
  [-1, 0], //up
  [0, 1], //right
  [1, 0], //down
  [0, -1] //left
]

const numberOfIslands = function(matrix) {
  if(matrix.length === 0) return 0;
  let islandCount = 0;

  for(let row = 0; row < matrix.length; row++) {
    for(let col = 0; col < matrix[0].length; col++) {
      if(matrix[row][col] === 1) {
        islandCount++;
        matrix[row][col] = 0;
        const queue = [];
        queue.push([row, col]);

        while(queue.length) {
          const currentPos = queue.shift();
          const currentRow = currentPos[0];
          const currentCol = currentPos[1];

          for(let i = 0; i < directions.length; i++) {
            const currentDir = directions[i];
            const nextRow = currentRow + currentDir[0];
            const nextCol = currentCol + currentDir[1];

            if(nextRow < 0 || nextRow >= matrix.length || nextCol < 0 || nextCol >= matrix[0].length) continue;

            if(matrix[nextRow][nextCol] === 1) {
              queue.push([nextRow, nextCol]);
              matrix[nextRow][nextCol] = 0;
            }
          }
        }
      }
    }
  }

  return islandCount;
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: Naming Your Componts Vue 
Javascript :: javascript online string concatenation 
Javascript :: mantine progress 
Javascript :: mongoose lookup array of objects 
Javascript :: Parsing the URL string using the Legacy API 
Javascript :: onclick add and remove class using jquery 
Javascript :: rpushx redis 
Javascript :: google apps script parse html 
Javascript :: cocos creator localstorage 
Javascript :: vite displays blank page in docker container 
Javascript :: v-if disable vue 
Javascript :: starting: intent error type 3 react-native 
Javascript :: check if a number is multiple of 3 javascript 
Javascript :: deep copy array of objects javascript 
Javascript :: react word cload 
Javascript :: how to get first and last 
Javascript :: cycle 2 
Javascript :: with jquery Make a style menu that displays paragraphs and hides them according to the style of the slides 
Javascript :: Why is node creating multiple server in cpanel 
Javascript :: alert title change 
Javascript :: i in javascript 
Javascript :: js 2 varibale points on same values 
Javascript :: react-icons/vsc 
Javascript :: angularjs checking array of objects 
Javascript :: js read html file 
Javascript :: How to hide div based on select the dropdown in angular js 
Javascript :: react table Maximum update depth exceeded. 
Javascript :: reverse array without using another array 
Javascript :: request submit form 
Javascript :: javascript encriment +1 
ADD CONTENT
Topic
Content
Source link
Name
7+2 =