Skip to content

Commit

Permalink
优化 选择器搜索控件的DFS算法,改递归为栈,加快速度并且避免出现StackOverflow的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
hyb1996 committed Jan 22, 2019
1 parent f6bab9e commit cfe6f92
Showing 1 changed file with 17 additions and 22 deletions.
39 changes: 17 additions & 22 deletions automator/src/main/java/com/stardust/automator/search/DFS.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -12,32 +13,26 @@ import kotlin.collections.ArrayList
object DFS : SearchAlgorithm {

override fun search(root: UiObject, filter: Filter, limit: Int): ArrayList<UiObject> {
val list = ArrayList<UiObject>()
if (filter.filter(root)) {
list.add(root)
if (list.size >= limit) {
return list
val result = ArrayList<UiObject>()
val stack = LinkedList<UiObject>()
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<UiObject>, 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
}

}

0 comments on commit cfe6f92

Please sign in to comment.