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; }
当你看清人们的真相,于是你知道了,你可以忍受孤独