알고리즘/알고리즘 문제풀이
배열_LeetCode_Queens That Can Attack the King
Downey
2021. 8. 6. 19:43
https://leetcode.com/problems/queens-that-can-attack-the-king/
접근 방법
1. queens.forEach()를 사용하여 왕의 가로 세로 대각선에 존재하는 지 검사하려고 함.
2. 가로와 세로를 코딩 한 이후 대각선을 검사하기 어렵다는 것을 깨닳음.
3. 머리를 아무리 싸매도 해결되지 않아, 이미 푼 선구자의 코드에서 힌트를 얻어 진행
4. 힌트 : direction: [Int]를 선언, x, y 방향으로 증감을 반복하여 queens의 여부를 확인
코드
Runtime: 12 ms, faster than 72.73% of Swift online submissions for Queens That Can Attack the King.
Memory Usage: 14 MB, less than 63.64% of Swift online submissions for Queens That Can Attack the King.
더보기
class Solution {
func queensAttacktheKing(_ queens: [[Int]], _ king: [Int]) -> [[Int]] {
var sol: [[Int]] = []
let directions = [-1, 0 ,1]
for dx in directions {
for dy in directions {
var x = king[0]
var y = king[1]
while x >= 0 && x < 8 && y >= 0 && y < 8 {
if dx == 0 && dy == 0 {
break
}
x += dx
y += dy
if queens.contains([x,y]) {
sol.append([x,y])
break
}
}
}
}
return sol
}
}