We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionconnectedCell(matrix){letlargestArea=0;constrows=matrix.length;constcols=matrix[0].length;for(leti=0;i<rows;i++){for(letj=0;j<cols;j++){if(matrix[i][j]===1){depthFirstSearch(matrix,i,j,0);// Start with area as 0}}}functiondepthFirstSearch(matrix,i,j,currentCell){if(i<0||i>=rows||j<0||j>=cols||matrix[i][j]===0){return;}currentCell++;largestArea=Math.max(largestArea,currentCell);matrix[i][j]=0;// Upper RowdepthFirstSearch(matrix,i-1,j-1,currentCell);depthFirstSearch(matrix,i-1,j,currentCell);depthFirstSearch(matrix,i-1,j+1,currentCell);// Current RowdepthFirstSearch(matrix,i,j-1,currentCell);depthFirstSearch(matrix,i,j+1,currentCell);// Lower RowdepthFirstSearch(matrix,i+1,j-1,currentCell);depthFirstSearch(matrix,i+1,j,currentCell);depthFirstSearch(matrix,i+1,j+1,currentCell);matrix[i][j]=1;}returnlargestArea;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Connected Cells in a Grid
You are viewing a single comment's thread. Return to all comments →
JavaScript solution inspired by other folks