Description
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.
Example 1:
Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
Output: [[0,1],[1,0],[3,3]]
Explanation:
The queen at [0,1] can attack the king cause they're in the same row.
The queen at [1,0] can attack the king cause they're in the same column.
The queen at [3,3] can attack the king cause they're in the same diagnal.
The queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1].
The queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0].
The queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.
Example 2:
Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
Output: [[2,2],[3,4],[4,4]]
Example 3:
Input: queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]
Output: [[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]
Constraints:
- 1 <= queens.length <= 63.
- queens[0].length == 2.
- 0 <= queens[i][j] < 8.
- king.length == 2.
- 0 <= king[0], king[1] < 8.
- At most one piece is allowed in a cell.
分析
题目的意思是:给定很多queen和king,问有多少个queen能够攻击到king,同行同列同对角线代表能够攻击,这道题跟我以前做的一个题目类似,所以思路就是从king出发左右上下对角线进行拓展,不过写出来的代码似乎不是很简洁,看了别人的实现,我简直哭晕在厕所,用一个数组定义所有的方向,是可以用两个循环搞定的,这个方向数组为:
directions = [[0,1],[1,0],[1,1],[-1,0],[0,-1],[-1,-1],[1,-1],[-1,1]]
代码
class Solution:
def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
x,y=king[0],king[1]
res=[]
for i in range(x-1,-1,-1):
x1,y1=i,y
if([x1,y1] in queens):
res.append([x1,y1])
break
for i in range(x+1,8,1):
x1,y1=i,y
if([x1,y1] in queens):
res.append([x1,y1])
break
for j in range(y-1,-1,-1):
x1,y1=x,j
if([x1,y1] in queens):
res.append([x1,y1])
break
for j in range(y+1,8,1):
x1,y1=x,j
if([x1,y1] in queens):
res.append([x1,y1])
break
i=x
j=y
while(i>=0 and j>=0):
i-=1
j-=1
if([i,j] in queens):
res.append([i,j])
break
i=x
j=y
while(i<8 and j<8):
i+=1
j+=1
if([i,j] in queens):
res.append([i,j])
break
i=x
j=y
while(i>=0 and j>=0):
i-=1
j+=1
if([i,j] in queens):
res.append([i,j])
break
i=x
j=y
while(i<8 and j<8):
i+=1
j-=1
if([i,j] in queens):
res.append([i,j])
break
return res

本文介绍了一个棋盘游戏问题:如何找出所有能攻击到国王的皇后。通过遍历八个可能的方向,文章提供了一种解决方案,该方案从国王的位置开始,沿行、列及对角线查找可以攻击到国王的皇后。
284

被折叠的 条评论
为什么被折叠?



