Java Simple Recursion Example - With Comments


  • 0
    K

    I understand that you can do this without modifying the board, but maybe someone will find this approach easier to grasp.

        public int countBattleships(char[][] board) {
            
            int ships = 0; //Number of ships
            
            //Loop over board
            for(int i = 0; i < board.length; i++) {
                for(int j = 0; j < board[0].length; j++) {
                    
                    //If 'X' is found
                    if(board[i][j] == 'X') {
                        ships++; //Increment ships count
                        clearCell(board, i, j); //Clear other ship cells
                    }
                    
                }
                
            }
            return ships;
        }
        
        //Sets current cell to '.' so it will be ignored when loop hits it
        public void clearCell(char[][] board, int col, int row) {
            
            board[col][row] = '.'; 
            
            //Check next column and row for an 'X' (if still within bounds of array)
            if(col + 1 < board.length && board[col+1][row] == 'X') 
                clearCell(board, col+1, row);
            else if(row + 1 < board[0].length && board[col][row+1] == 'X') 
                clearCell(board, col, row+1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.