码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "419. Battleships in a Board"

时间:2017-01-06 08:02:17      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:return   could   sed   ttl   nbsp   app   modify   when   extra   

The follow-up question is fun: "Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?"

When we meet an ‘X‘, we need to check if it is vertical or horizontal: they will never happen at the same time, by problem statement. For horizontal, we simply stripe through right, and plus 1 - however, if our top element is ‘X‘ already, it is a vertical and counter has alread been increased.

class Solution {
public:
    int countBattleships(vector<vector<char>>& board) {
        int h = board.size();
        if (!h) return 0;
        int w = board[0].size();
        if (!w) return 0;
        
        int cnt = 0;
        for(int i = 0; i < h; i ++)
        for(int j = 0; j < w; j ++)
        {
            if(board[i][j] == X) 
            {
                // is it a counted vertical case?
                if(!(i > 0 && board[i -1][j] == X))
                {
                    cnt ++;
                    // Horizontal
                    while(j < (w - 1) && board[i][j + 1] == X) j ++;
                }
            }
        }
        
        return cnt;
    }
};

LeetCode "419. Battleships in a Board"

标签:return   could   sed   ttl   nbsp   app   modify   when   extra   

原文地址:http://www.cnblogs.com/tonix/p/6254871.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!