📌  相关文章
📜  检查给定的二维点是否形成T形

📅  最后修改于: 2021-06-26 08:59:28             🧑  作者: Mango

给定5个2维点的坐标,请检查它们是否形成闭合的T形。如果它们形成T形,则打印“是”,否则,则打印“否”。注意:坐标应该是不同的并且是整数。
根据给定条件,可能有4种类型的T形地层:

例子:

Input: [[7, 5], [8, 5], [6, 5], [7, 7], [7, 6]]
Output: Yes

Input: [[0, 0], [1, 0], [2, 0], [1, -1], [1, -2]]
Output: Yes

方法:

  1. 将给定列表中的第一个点视为中心(x,y)(即,形成T形的两条线的交点)。
  2. 然后检查在给定点列表中是否存在形成(x,y)为中心的T形所需的所有点。
  3. 选中所有4种可能的T形图案。

下面是上述方法的实现:

Python3
# Python3 code to check if given 5
# 2-D points form T-shape or not
 
# Import the function to initialize the
# dictionary with a specific value
from collections import defaultdict
 
# This function checks if the points
# form T-shape pointing up
 
 
def isUpDirected(point, x, y):
 
    return (point[(x-1, y)] and
            point[(x, y)] and
            point[(x + 1, y)] and
            point[(x, y-1)] and
            point[(x, y-2)])
 
# This function checks if the points
# form T-shape pointing down
 
 
def isDownDirected(point, x, y):
 
    return (point[(x-1, y)] and
            point[(x, y)] and
            point[(x + 1, y)] and
            point[(x, y + 1)] and
            point[(x, y + 2)])
 
# This function checks if the points
# form T-shape pointing left
 
 
def isLeftDirected(point, x, y):
 
    return (point[(x, y + 1)] and
            point[(x, y)] and
            point[(x, y-1)] and
            point[(x + 1, y)] and
            point[(x + 2, y)])
 
# This function checks if the points
# form T-shape pointing right
 
 
def isRightDirected(point, x, y):
 
    return (point[(x, y + 1)] and
            point[(x, y)] and
            point[(x, y-1)] and
            point[(x-1, y)] and
            point[(x-2, y)])
 
 
# This function checks if given points
# form a T-shape or not
def solve(grid):
 
    # Initialize the dictionary with False value
    point = defaultdict(lambda: False)
    flag = False
 
    for i in range(len(grid)):
 
        # Assign True value to the points which
        # are present in the given list
        point[(grid[i][0], grid[i][1])] = True
 
    for i in range(len(grid)):
 
        # Check if the given points form any of the
        # 4 possible T-shaped formations
        if isUpDirected(point, grid[i][0], grid[i][1]) or
           isDownDirected(point, grid[i][0], grid[i][1]) or
            isLeftDirected(point, grid[i][0], grid[i][1]) or
            isRightDirected(point, grid[i][0], grid[i][1]):
 
            flag = True
            break
 
    if flag == True:
        return 'Yes'
    else:
        return 'No'
 
 
print(solve([[7, 5], [8, 5], [6, 5], [7, 7], [7, 6]]))
print(solve([[0, 0], [1, 0], [2, 0], [1, -1], [1, -2]]))


输出:
Yes
Yes

时间复杂度: O(1)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。