1. 程式人生 > >[算法]Python實現

[算法]Python實現

== clas ++ class 全部 urn 多邊形 info odin

題目:

技術分享圖片

代碼:

# -*- coding:utf-8 -*-

def rayCasting(p, poly):
    px = p[‘x‘]
    py = p[‘y‘]
    flag = False

    i = 0
    l = len(poly)
    j = l - 1
    #for(i = 0, l = poly.length, j = l - 1; i < l; j = i, i++):
    while i < l:
        sx = poly[i][‘x‘]
        sy = poly[i][‘y‘]
        tx = poly[j][‘x‘]
        ty = poly[j][‘y‘]

        #點與多邊形頂點重合
        if (sx == px and sy == py) or (tx == px and ty == py):
            return (px, py)

        #判斷線段兩端點是否在射線兩側
        if (sy < py and ty >= py) or (sy >= py and ty < py):
            #線段上與射線 Y 坐標相同的點的 X 坐標
            x = sx + (py - sy) * (tx - sx) / (ty - sy)
            #點在多邊形的邊上
            if x == px:
                return (px,py)
            #射線穿過多邊形的邊界
            if x > px:
                flag = not flag
        j = i
        i += 1

    #射線穿過多邊形邊界的次數為奇數時點在多邊形內
    return (px,py) if flag else ‘out‘

#根據數組下標奇偶數得到點的坐標
def getpoint(a):
    i = 0
    zhima = []
    while i < len(a.split(‘,‘)[1::2]):
        zhima.append({‘x‘: float(a.split(‘,‘)[::2][i]),‘y‘: float(a.split(‘,‘)[1::2][i])})
        i += 1
    return zhima

#根據輸入的點循環判斷芝麻是否在多邊形裏面,如果全部在外面則輸出no,否則輸出芝麻的坐標
def rs(zhima, duobianxing):
    zm = getpoint(zhima)
    dbx = getpoint(duobianxing)
    count = 0
    for point in zm:
        rs = rayCasting(point, dbx)
        if rs == ‘out‘:
            count += 1
        else:
            print rs
    if count == len(zm):
        print "no"


zhima = "6,4,8,8,9,9"
duobianxing = "1,1,7,3,5,7"
rs(zhima,duobianxing)

  

結果:

技術分享圖片

[算法]Python實現