欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 1222. Queens That Can Attack the King

程序员文章站 2022-07-15 09:43:30
...

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.
LeetCode 1222. Queens That Can Attack the King
LeetCode 1222. Queens That Can Attack the King
LeetCode 1222. Queens 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

相关标签: leetcode python