From cfe6f92e1325f4275e390f50fca25951edf2dd53 Mon Sep 17 00:00:00 2001 From: hyb1996 <946994919@qq.com> Date: Tue, 22 Jan 2019 20:33:59 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E5=99=A8=E6=90=9C=E7=B4=A2=E6=8E=A7=E4=BB=B6=E7=9A=84DFS?= =?UTF-8?q?=E7=AE=97=E6=B3=95=EF=BC=8C=E6=94=B9=E9=80=92=E5=BD=92=E4=B8=BA?= =?UTF-8?q?=E6=A0=88=EF=BC=8C=E5=8A=A0=E5=BF=AB=E9=80=9F=E5=BA=A6=E5=B9=B6?= =?UTF-8?q?=E4=B8=94=E9=81=BF=E5=85=8D=E5=87=BA=E7=8E=B0StackOverflow?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/stardust/automator/search/DFS.kt | 39 ++++++++----------- 1 file changed, 17 insertions(+), 22 deletions(-) diff --git a/automator/src/main/java/com/stardust/automator/search/DFS.kt b/automator/src/main/java/com/stardust/automator/search/DFS.kt index 6f7efdd8a..005bd3fb7 100644 --- a/automator/src/main/java/com/stardust/automator/search/DFS.kt +++ b/automator/src/main/java/com/stardust/automator/search/DFS.kt @@ -2,6 +2,7 @@ package com.stardust.automator.search import com.stardust.automator.UiObject import com.stardust.automator.filter.Filter +import java.util.* import kotlin.collections.ArrayList @@ -12,32 +13,26 @@ import kotlin.collections.ArrayList object DFS : SearchAlgorithm { override fun search(root: UiObject, filter: Filter, limit: Int): ArrayList { - val list = ArrayList() - if (filter.filter(root)) { - list.add(root) - if (list.size >= limit) { - return list + val result = ArrayList() + val stack = LinkedList() + stack.push(root) + while (stack.isNotEmpty()) { + val parent = stack.pop() + for (i in parent.childCount - 1 downTo 0) { + val child = parent.child(i) ?: continue + stack.push(child) } - } - searchChildren(root, list, filter, limit) - return list - } - - private fun searchChildren(parent: UiObject, list: MutableList, filter: Filter, limit: Int) { - for (i in 0 until parent.childCount) { - val child = parent.child(i) ?: continue - val isTarget = filter.filter(child) - if (isTarget) { - list.add(child) - if (list.size >= limit) { + if (filter.filter(parent)) { + result.add(parent) + if (result.size >= limit) { break } - } - searchChildren(child, list, filter, limit) - if (!isTarget) { - child.recycle() + } else { + if (parent !== root) { + parent.recycle() + } } } + return result } - }