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:
                        break
                    if (i,j) in queens:
                        res.append([i,j])
                        break
        return res

Reference

https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/403669/Python-Check-8-steps-in-8-Directions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值