骨骼清奇BFS+DSU

Catalog:
LC 三九九 Evaluate Division
LC 六八四 六八五及其變種(Tree刪除額外邊)
LC 803 Bricks Falling When Hit
LC 505 The Maze II

todo:
[Uber] LC 286 Walls and Gates

LC三九九及其變種(匯率)Evaluate Division
頻率:21

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction. . If the answer does not exist, return -1.0.
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

分析:首先構(gòu)建一個(gè)graph(注意正反相除,自身相除)橄唬,如果A和B,C有關(guān)系,那么B和C就可以利用A作為橋梁進(jìn)行相除(換匯)讼撒。可以DFS股耽,也可以把所有可能的通道都建立起來(lái)根盒。

#Runtime: 68 ms
class Solution:
    def calcEquation(self, equations, values, queries):
        """
        :type equations: List[List[str]]
        :type values: List[float]
        :type queries: List[List[str]]
        :rtype: List[float]
        """
        
        graph = collections.defaultdict(dict)
        for (n1, n2), val in zip(equations, values):
            graph[n1][n1] = graph[n2][n2] = 1.0
            graph[n1][n2] = val
            graph[n2][n1] = 1 / val
        for k in graph:
            for i in graph[k]:
                for j in graph[k]:
                    graph[i][j] = graph[i][k] * graph[k][j]
        
        return [graph[n1].get(n2, -1.0) for n1, n2 in queries]

迭代的方式做BFS, 36ms!

class Solution(object):
    def calcEquation(self, equations, values, queries):
        """
        :type equations: List[List[str]]
        :type values: List[float]
        :type queries: List[List[str]]
        :rtype: List[float]
        """
        graph = collections.defaultdict(dict)
        for (n1, n2), val in zip(equations, values):
            #graph[n1][n1] = graph[n2][n2] = 1.0
            graph[n1][n2] = val
            graph[n2][n1] = 1 / val

        def getVal(st, en):
            visited = set()
            q = [(node, val) for node, val in graph[st].items()]
            while q:
                nextl = set()
                while q:
                    node, val= q.pop(0)
                    if node == en:
                        return val
                    visited.add(node)
                    for nnode, nval in graph[node].items():
                        if nnode not in visited:
                            nextl.add((nnode, nval*val))
                q = list(nextl)
            return -1
        
        res = []
        for x, y in queries:
            if x not in graph or y not in graph:
                res.append(-1.0)
            elif x == y:
                res.append(1.0)
            else:
                res.append(getVal(x, y))
        return res

LC六八四 六八五及其變種(Tree刪除額外邊)
頻率:10

A tree is an undirected graph that is connected and has no cycles. The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added.
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.

分析:Union Find or DFS

the directed graph follow up - [Redundant Connection II].

  1. Bus Routes [Freq:5]
    what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
    routes = [[1, 2, 7], [3, 6, 7]]
    S = 1
    T = 6
    Output: 2
    Explanation:
    The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.

Key: BFS, Memo.
Corner Case: start at intersection. start and end in the same route/stop.

class Solution(object):
    def numBusesToDestination(self, routes, S, T):
        if S == T: return 0
        routes = map(set, routes)
        graph = collections.defaultdict(set)
        for i, r1 in enumerate(routes):
            for j in range(i+1, len(routes)):
                r2 = routes[j]
                if any(stop in r2 for stop in r1):
                    graph[i].add(j)
                    graph[j].add(i)

        seen, targets = set(), set()
        for node, route in enumerate(routes):
            if S in route: seen.add(node)
            if T in route: targets.add(node)

        queue = [(node, 1) for node in seen]
        for node, depth in queue:
            if node in targets: return depth
            for nei in graph[node]:
                if nei not in seen:
                    seen.add(nei)
                    queue.append((nei, depth+1))
        return -1

?Time Complexity:

  1. To create the graph, in Python we do O(∑(N?i)bi), where N denotes the number of buses, and bi
    ?is the number of stops on the ith bus.
    2.BFS is on N nodes, and each node could have N edges, so it is O(N^2)
    ?Space Complexity: O(N^2 + ∑bi)
class DSU:
    def __init__(self, R, C):
        #R * C is the source, and isn't a grid square
        self.par = range(R*C + 1)
        self.rnk = [0] * (R*C + 1)
        self.sz = [1] * (R*C + 1)

    def find(self, x):
        if self.par[x] != x:
            self.par[x] = self.find(self.par[x])
        return self.par[x]

    def union(self, x, y):
        xr, yr = self.find(x), self.find(y)
        if xr == yr: return
        if self.rnk[xr] < self.rnk[yr]:
            xr, yr = yr, xr
        if self.rnk[xr] == self.rnk[yr]:
            self.rnk[xr] += 1

        self.par[yr] = xr
        self.sz[xr] += self.sz[yr]

    def size(self, x):
        return self.sz[self.find(x)]

    def top(self):
        # Size of component at ephemeral "source" node at index R*C,
        # minus 1 to not count the source itself in the size
        return self.size(len(self.sz) - 1) - 1

LC803 Bricks Falling When Hit
> Return an array representing the number of bricks that will drop after each erasure in sequence.

> grid = [[1,0,0,0],[1,1,0,0]]
hits = [[1,1],[1,0]]
Output: [0,0]

> grid = [[1,0,0,0],[1,1,1,0]]
hits = [[1,0]]
Output: [2]

Reverse Time and Union-Find

class Solution(object):
    def hitBricks(self, grid, hits):
        R, C = len(grid), len(grid[0])
        def index(r, c):
            return r * C + c

        def neighbors(r, c):
            for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)):
                if 0 <= nr < R and 0 <= nc < C:
                    yield nr, nc

        A = [row[:] for row in grid]
        for i, j in hits:
            A[i][j] = 0

        dsu = DSU(R, C)
        for r, row in enumerate(A):
            for c, val in enumerate(row):
                if val:
                    i = index(r, c)
                    if r == 0:
                        dsu.union(i, R*C)
                    if r and A[r-1][c]:
                        dsu.union(i, index(r-1, c))
                    if c and A[r][c-1]:
                        dsu.union(i, index(r, c-1))

        ans = []
        for r, c in reversed(hits):
            pre_roof = dsu.top()
            if grid[r][c] == 0:
                ans.append(0)
            else:
                i = index(r, c)
                for nr, nc in neighbors(r, c):
                    if A[nr][nc]:
                        dsu.union(i, index(nr, nc))
                if r == 0:
                    dsu.union(i, R*C)
                A[r][c] = 1
                ans.append(max(0, dsu.top() - pre_roof - 1))
        return ans[::-1]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市物蝙,隨后出現(xiàn)的幾起案子炎滞,更是在濱河造成了極大的恐慌,老刑警劉巖诬乞,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件册赛,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡震嫉,警方通過(guò)查閱死者的電腦和手機(jī)森瘪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)票堵,“玉大人扼睬,你說(shuō)我怎么就攤上這事°彩疲” “怎么了窗宇?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)特纤。 經(jīng)常有香客問(wèn)我军俊,道長(zhǎng),這世上最難降的妖魔是什么捧存? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任粪躬,我火速辦了婚禮,結(jié)果婚禮上昔穴,老公的妹妹穿的比我還像新娘镰官。我一直安慰自己,他們只是感情好傻咖,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著岖研,像睡著了一般卿操。 火紅的嫁衣襯著肌膚如雪警检。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,443評(píng)論 1 302
  • 那天害淤,我揣著相機(jī)與錄音扇雕,去河邊找鬼。 笑死窥摄,一個(gè)胖子當(dāng)著我的面吹牛镶奉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播崭放,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼哨苛,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了币砂?” 一聲冷哼從身側(cè)響起建峭,我...
    開(kāi)封第一講書(shū)人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎决摧,沒(méi)想到半個(gè)月后亿蒸,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡掌桩,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年边锁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片波岛。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茅坛,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出盆色,到底是詐尸還是另有隱情灰蛙,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布隔躲,位于F島的核電站摩梧,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏宣旱。R本人自食惡果不足惜仅父,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望浑吟。 院中可真熱鬧笙纤,春花似錦、人聲如沸组力。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)燎字。三九已至腥椒,卻和暖如春阿宅,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背笼蛛。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工洒放, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人滨砍。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓往湿,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親惋戏。 傳聞我的和親對(duì)象是個(gè)殘疾皇子领追,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,325評(píng)論 0 10
  • 專業(yè)考題類型管理運(yùn)行工作負(fù)責(zé)人一般作業(yè)考題內(nèi)容選項(xiàng)A選項(xiàng)B選項(xiàng)C選項(xiàng)D選項(xiàng)E選項(xiàng)F正確答案 變電單選GYSZ本規(guī)程...
    小白兔去釣魚(yú)閱讀 8,988評(píng)論 0 13
  • 我不是故意的,這樣說(shuō)有些牽強(qiáng)日川。 作為主公選擇武則天挺厲害的蔓腐,條件是壞人們都是男性,因?yàn)檫@樣媚娘的決鬥才會(huì)發(fā)揮最大的...
    宋小朝閱讀 149評(píng)論 0 0
  • 為什么復(fù)制到這里沒(méi)有一點(diǎn)格式了龄句!復(fù)習(xí)的話還是到筆記中復(fù)習(xí)吧回论! Extract:解壓folder;文件夾elemen...
    Easy_wjc閱讀 670評(píng)論 1 0
  • 還記得電視劇《仙劍奇?zhèn)b傳三》里的道士徐長(zhǎng)卿和女媧后人紫萱虐人的三生三世的愛(ài)戀嗎?也許就像歌詞里說(shuō)的职抡,分散太難葬燎,相守...
    青青如微閱讀 663評(píng)論 2 0