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.
classResult{publicstaticStringcountLuck(List<String>matrix,intk){introws=matrix.size();intcols=matrix.get(0).length();char[][]matrixArr=newchar[rows][cols];intstartX=-1;intstartY=-1;// Parse the input matrix into a 2D char array and locate the starting position 'M'for(inti=0;i<rows;i++){for(intj=0;j<cols;j++){matrixArr[i][j]=matrix.get(i).charAt(j);if(matrixArr[i][j]=='M'){startX=i;startY=j;}}}// Count the "waves" (decision points) to determine the pathintwaves=getWaves(matrixArr,startX,startY);// Return "Impressed" if the waves match k, otherwise "Oops!"returnwaves==k?"Impressed":"Oops!";}privatestaticintgetWaves(char[][]matrixArr,intstartX,intstartY){int[][]directions={{0,1},{1,0},{0,-1},{-1,0}};Queue<int[]>cells=newLinkedList<>();boolean[][]visited=newboolean[matrixArr.length][matrixArr[0].length];cells.offer(newint[]{startX,startY,0});// Starting position and wave countwhile(!cells.isEmpty()){int[]curCellPos=cells.poll();intcurX=curCellPos[0];intcurY=curCellPos[1];intwaveCount=curCellPos[2];// If the current cell is the destination '*', return the wave countif(matrixArr[curX][curY]=='*'){returnwaveCount;}// Mark the current cell as visitedvisited[curX][curY]=true;// Check if the current cell is a decision point and increase wave count if trueif(isDecisionPoint(matrixArr,visited,curX,curY)){waveCount++;}// Add valid neighboring cells to the queuefor(int[]dir:directions){intnewX=curX+dir[0];intnewY=curY+dir[1];if(isValid(matrixArr,newX,newY)&&(matrixArr[newX][newY]=='.'||matrixArr[newX][newY]=='*')&&!visited[newX][newY]){cells.offer(newint[]{newX,newY,waveCount});}}}// Return 0 if the destination is unreachable (edge case)return0;}privatestaticbooleanisDecisionPoint(char[][]matrixArr,boolean[][]visited,intx,inty){int[][]directions={{0,1},{1,0},{0,-1},{-1,0}};intpaths=0;// Check all four directions for valid and unvisited pathsfor(int[]dir:directions){intnewX=x+dir[0];intnewY=y+dir[1];if(isValid(matrixArr,newX,newY)&&(matrixArr[newX][newY]=='.'||matrixArr[newX][newY]=='*')&&!visited[newX][newY]){paths++;}}// A decision point occurs when there is more than one valid pathreturnpaths>1;}privatestaticbooleanisValid(char[][]matrixArr,intx,inty){introws=matrixArr.length;intcols=matrixArr[0].length;// Check if the coordinates are within boundsreturnx>=0&&x<rows&&y>=0&&y<cols;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Count Luck
You are viewing a single comment's thread. Return to all comments →
Java using BFS