leetcode.com/problems/battleships-in-a-board/
Battleships in a Board - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
요렇게 생각할 수 있겠으나
class Solution {
public int countBattleships(char[][] board) {
int res = 0, m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'X') {
res++;
helper(board, i, j);
}
}
}
return res;
}
public void helper(char[][] board, int i, int j) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != 'X')
return;
board[i][j] = '.';
helper(board, i, j - 1);
helper(board, i + 1, j);
helper(board, i, j + 1);
helper(board, i - 1, j);
}
}
요고
class Solution {
public int countBattleships(char[][] board) {
int r = board.length;
if(r == 0) return 0;
int c = board[0].length;
int count = 0;
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
if(board[i][j] == '.') continue;
if(i > 0 && board[i-1][j] == 'X') continue;
if(j > 0 && board[i][j-1] == 'X') continue;
count++;
}
}
return count;
}
}
www.youtube.com/watch?v=zSQIGzmcp2I
내 블로그 - 관리자 홈 전환 |
Q
Q
|
---|---|
새 글 쓰기 |
W
W
|
글 수정 (권한 있는 경우) |
E
E
|
---|---|
댓글 영역으로 이동 |
C
C
|
이 페이지의 URL 복사 |
S
S
|
---|---|
맨 위로 이동 |
T
T
|
티스토리 홈 이동 |
H
H
|
단축키 안내 |
Shift + /
⇧ + /
|
* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.