Leetcode 419. Battleships in a Board
来源:互联网 发布:非常完美知乎 编辑:程序博客网 时间:2024/05/08 05:01
原题链接:
思路:如果当前位置是’X’,并且他的左边和上边都不是’X’,就表示这是一个新的战舰。避免递归,并且只需遍历一遍,同时满足O(1)空间复杂度的解法(PS:然而只打败了3%的人,测试数据让我很无语。。。)
class Solution { public int countBattleships(char[][] board) { if(board.length == 0 || board[0].length == 0){ return 0; } int ans = 0; if(board[0][0] == 'X'){ ans++; } for(int i = 1; i < board.length; i++){ if(board[i][0] == 'X' && board[i - 1][0] != 'X'){ ans++; } } for(int i = 1; i < board[0].length; i++){ if(board[0][i] == 'X' && board[0][i - 1] != 'X'){ ans++; } } for(int i = 1; i < board.length; i++){ for(int j = 1; j < board[0].length; j++){ if(board[i][j] == 'X' && board[i - 1][j] != 'X' && board[i][j - 1] != 'X'){ ans++; } } } return ans; }}
阅读全文
0 0
- 【leetcode】419. Battleships in a Board【E】
- Leetcode题解:419. Battleships in a Board
- 419. [LeetCode]Battleships in a Board
- LeetCode 419. Battleships in a Board
- leetcode 419. Battleships in a Board
- LeetCode笔记:419. Battleships in a Board
- LeetCode 419. Battleships in a Board
- [leetcode]419. Battleships in a Board
- 【LeetCode】 419. Battleships in a Board
- LeetCode--419. Battleships in a Board
- LeetCode 419. Battleships in a Board
- [leetcode]419. Battleships in a Board
- Leetcode-419. Battleships in a Board
- 【LeetCode】419. Battleships in a Board
- LeetCode:419. Battleships in a Board
- [LeetCode]419. Battleships in a Board
- [LeetCode]419. Battleships in a Board
- 【LeetCode】419. Battleships in a Board
- Realtime Multi-Person 2D Pose Estimation using Part Affinity Fields ∗ 实时多人人体姿态估计论文原理讲解
- CentOS 7.2 yum安装LAMP环境
- Python GUI之tkinter 实战(二)
- Zynq平台下linux的I2C驱动(RTC+EEPROM)
- Java实现二分查找算法
- Leetcode 419. Battleships in a Board
- Windows 10 下如何彻底关闭 Hyper-V 服务(翻外篇)
- close与shutdown
- MHA配置参数解释
- (4) Hadoop-MapReduce计算模型
- 时间戳转换
- Linux下使用I2C总线读写 EEPROM(读写i2c从设备通用程序)
- (8) Hadoop-工作流调度器azkanban
- 二叉树的基本操作