반응형
https://leetcode.com/problems/available-captures-for-rook/description/
LeetCode - The World's Leading Online Programming Learning Platform
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
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
1. {행, 열}을 저장할 struct Coord를 선언합니다.
2. 정답변수 ans를 선언해줍니다.
📔 풀이과정
1. rook의 행, 열 좌표를 loop를 수행해 찾아 변수 rookCoord에 저장합니다.2. rookCoord를 중심으로 좌, 우, 상, 하로 직선으로 각각 뻗어나가며 pawn공격 가능 개수를 구해 정답 변수 ans에 더해줍니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
struct Coord {
int row, col;
};
class Solution {
public:
int countIntDirection(vector<vector<char>>& board, Coord start, Coord delta) {
int count = 0;
for(int i = 1;; i++) {
int row = start.row + i * delta.row;
int col = start.col + i * delta.col;
if(0 > row || row >= board.size() || 0 > col || col >= board[0].size()) break;
if(board[row][col] == 'B') break;
if(board[row][col] == 'p') {
count++;
break;
}
}
return count;
}
int numRookCaptures(vector<vector<char>>& board) {
Coord rookCoord;
int ans = 0;
for(int i = 0; i < board.size(); i++) {
for(int j = 0; j < board[0].size(); j++) {
if(board[i][j] == 'R') rookCoord = {i, j};
}
}
ans += countIntDirection(board, rookCoord, {0,-1}); //좌
ans += countIntDirection(board, rookCoord, {0, 1}); //우
ans += countIntDirection(board, rookCoord, {-1,0}); //상
ans += countIntDirection(board, rookCoord, {1, 0}); //하
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++, Rust) - LeetCode (easy) 1013. Partition Array Into Three Parts With Equal Sum (0) | 2023.10.04 |
---|---|
(C++, Rust) - LeetCode (easy) 1009. Complement of Base 10 Integer (0) | 2023.09.26 |
(Python3) - LeetCode (easy) 989. Add to Array-Form of Integer (0) | 2023.09.18 |
(C++, Rust) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.11 |
(C++) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.08 |