Java simple logic


  • 0

    the starting point of battleship is not connected to other battleship. You only need to check previously visited cell.

    public class Solution {
        public int countBattleships(char[][] board) {
            int count = 0;
            int m = board.length;
            int n = board[0].length;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if ((board[i][j] == 'X') &&
                        (i - 1 < 0 || board[i - 1][j] == '.') && 
                        (j - 1 < 0 || board[i][j - 1] == '.') ) {
                        count++;
                    }
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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