[leetcode-419-Battleships in a Board]
Posted hellowOOOrld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-419-Battleships in a Board]相关的知识,希望对你有一定的参考价值。
Given an 2D board, count how many battleships are in it. The battleships are represented with \'X\'
s, empty slots are represented with \'.\'
s. You may assume the following rules:
- You receive a valid board, made of only battleships or empty slots.
- Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape
1xN
(1 row, N columns) orNx1
(N rows, 1 column), where N can be of any size. - At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
Example:
X..X ...X ...XIn the above board there are 2 battleships.
Invalid Example:
...X XXXX ...XThis is an invalid board that you will not receive - as battleships will always have a cell separating between them.
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
思路:
首先想到dfs。
void dfsbattle(vector<vector<char>>& board,vector<vector<bool>>& visited,int i,int j) { int m = board.size(), n = board[0].size(); if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] || board[i][j] == \'.\')return; visited[i][j] = true; dfsbattle(board, visited, i + 1, j); dfsbattle(board, visited, i - 1, j); dfsbattle(board, visited, i , j+1); dfsbattle(board, visited, i , j-1); } int countBattleships(vector<vector<char>>& board) { if (board.empty())return 0; int m = board.size(), n = board[0].size(); vector<vector<bool>>visited(m, vector<bool>(n, false)); int ret = 0; for (int i = 0; i < m;i++) { for (int j = 0; j < n;j++) { if (board[i][j]==\'X\'&& !visited[i][j]) { dfsbattle(board, visited, i,j); ret++; } } } return ret; }
又题目提到不用额外空间,而且只遍历一次。。
public int countBattleships(char[][] board) { int count = 0; for(int i=0;i<board.length;i++) for(int j=0;j<board[0].length;j++) if(board[i][j]==\'X\' && (i==0 || board[i-1][j]!=\'X\') && (j==0 || board[i][j-1]!=\'X\')) count++; return count; }
参考:
https://discuss.leetcode.com/topic/64027/share-my-7-line-code-1-line-core-code-3ms-super-easy
以上是关于[leetcode-419-Battleships in a Board]的主要内容,如果未能解决你的问题,请参考以下文章