LeetCode:419. Battleships in a Board

来源:互联网 发布:机器人编程入门视频 编辑:程序博客网 时间:2024/05/23 00:13

今天还想再刷一道题,做算法题好像心都静下来了!

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) or Nx1 (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.

-----------------------------------------------------------------我是分割线----------------------------------------------------------------------

题目原意是:水平方向或者竖直方向上的'X'集合算一条军舰,不能拐弯,不会出现两条军舰挨着的情况。

通过仔细观察发现:军舰开头位置为X,它的上面必须为“_”,它的左边必须为“_”。需要特殊考虑最上面的情况和最左边的情况。通过全部遍历这个二维数组,找到船的开头,记为找到一个军舰。代码如下:

class Solution{public:int countBattleships(vector<vector<char>>&board){if(board.empty()||board[0].empty())return 0;int value=0;int m=board.size();int n=board[0].size();for(int i=0;i<m;i++){for(int j=0;j<n;j++){if(board[i][j]=='X'&&(i>0||board[i-1][j]=='_'&&(j>0||board[i][j-1]=='X'))){continue;++value;}}}return value;}}; 
同时,还可以通过深度优先算法来实现。深度优先算法用最简单的语言表示就是:一条路走到黑,然后再倒回来再选择一条路走到黑。直到将所有路遍历完全。本题比较简单,两艘船之间肯定会有“_”间隔。代码如下:

class Solution{private:vector<vector<bool>> visited;int rsize,csize;int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};public:void dfs(vector<vector<char>>&board,int i,int j){if(i<0||j<0||i>rsize||j>csize||board[i][j]=='_'||visited[i][j])return;visited[i][j]=true;for(int d=0;d<4;d++){dfs(board,i+board[d][0],j+board[d][1]);}}int countBattleships(vector<vector<char>>&board){if (board.empty())            return 0;        rsize = board.size();        csize = board[0].size();        visited.resize(rsize, vector<bool>(csize, false));        int count = 0; for (int i = 0; i < rsize; i++) {            for (int j = 0; j < csize; j++) {                if (board[i][j] == 'X' && !visited[i][j]) {                    count++;                    dfs(board, i, j);                }            }        }        return count;}}; 


0 0
原创粉丝点击