The most easiest way to battleships in a board C++ O(1) space and O(n) time


  • 0
    D
    public:
        bool isbattleship(int i, int j, vector<vector<char>> & board){
            if(board[i][j] != 'X') return false;
            else{ 
                if(i - 1 == -1 && j - 1 == -1) return true;
                if(i - 1 == -1)
                    return (board[i][j-1] == 'X')? false:true;
                if(j - 1 == -1)
                    return (board[i-1][j] == 'X')? false:true;
                return (board[i-1][j]=='X' || board[i][j-1]=='X')? false:true;
            }
        } 
        int countBattleships(vector<vector<char>>& board) {
            int cnt = 0;
            for(int i = 0; i < board.size(); ++i)
                for(int j = 0; j < board[0].size(); ++j)
                    if(isbattleship(i,j,board) == true) cnt++;
            return cnt;
        }
    };

Log in to reply
 

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