本文主要是介绍LeetCode 1222. Queens That Can Attack the King解题报告,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
LeetCode 1222. Queens That Can Attack the King
LeetCode 1222. Queens That Can Attack the King python solution
题目描述
On an 8x8 chessboard, there can be multiple Black Queens and one White King.
Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.
解析
本题的解题思路很简单,遍历八个方向,寻找最近的queen,由内向外扩散找到最近的皇后时,停止寻找。使用3个循环完成8各方向的搜索。
// An highlighted block
class Solution:def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:res=[]queens={(i,j) for i,j in queens}for x in [-1,0,1]:for y in [-1,0,1]:for t in range(0,8):i=king[0]+(x*t)j=king[1]+(y*t)if i<0 or i>7 or j<0 or j>7:breakif (i,j) in queens:res.append([i,j])breakreturn res
Reference
https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/403669/Python-Check-8-steps-in-8-Directions
这篇关于LeetCode 1222. Queens That Can Attack the King解题报告的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!