zoukankan      html  css  js  c++  java
  • Leetcode 419 甲板上的战舰 一次扫描

     

      JAVA DFS 标记解法:

    public final int countBattleshipsDFS(char[][] board) {
            if (board.length == 0 || board[0].length == 0) return 0;
            int res = 0;
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == 'X') {
                        sign(board, i, j);
                        res++;
                    }
                }
            }
            return res;
        }
    
        private final void sign(char[][] board, int x, int y) {
            if (x < 0 || y < 0 || x >= board.length || y >= board[0].length) return;
            if (board[x][y] != 'X') return;
            board[x][y] = '-';
            sign(board, x + 1, y);
            sign(board, x - 1, y);
            sign(board, x, y + 1);
            sign(board, x, y - 1);
        }

      进阶,JAVA 一次扫描,空间复杂度 O(1) 且不改变数组的值:

        public final int countBattleships(char[][] board) {
            int res = 0;
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (board[i][j] == 'X') {
                        if ((i == 0 || (i > 0 && board[i - 1][j] != 'X')) && (j == 0 || (j > 0 && board[i][j - 1] != 'X')))
                            res++;
                    }
                }
            }
            return res;
        }

      JS DFS 标记解法:

    /**
     * @param {character[][]} board
     * @return {number}
     */
    var countBattleships = function (board) {
        if (board.length == 0 || board[0].length == 0) return 0;
    
        function sign(x, y) {
            if (x < 0 || y < 0 || x >= board.length || y >= board[0].length || board[x][y] != 'X') return;
            board[x][y] = '-';
            sign(x + 1, y);
            sign(x - 1, y);
            sign(x, y + 1);
            sign(x, y - 1);
        }
    
        let res = 0;
        for (let i = 0; i < board.length; i++) {
            for (let j = 0; j < board[0].length; j++) {
                if (board[i][j] != 'X') continue;
                sign(i, j);
                res++;
            }
        }
        return res;
    };

      JS 一次扫描,O(1) 空间复杂度且不改变数组的值:

    var countBattleships = function (board) {
        let res = 0;
        for (let i = 0; i < board.length; i++) {
            for (let j = 0; j < board[0].length; j++) {
                if (board[i][j] != 'X') continue;
                if ((i == 0 || board[i - 1][j] != 'X') && (j == 0 || board[i][j - 1] != 'X')) res++;
            }
        }
        return res;
    }

  • 相关阅读:
    湾区求职分享:三个月刷题拿到 Google offer,欢迎踊跃提问
    【转】关于写书
    【转】真相
    【转】成都的雾霾
    【转】iPhone X
    【转】网络用语
    【转】AlphaGo Zero 和强人工智能
    【转】理性的力量
    【转】旅行的智慧
    【转】我为什么爱猫
  • 原文地址:https://www.cnblogs.com/niuyourou/p/13710165.html
Copyright © 2011-2022 走看看