我有以下实体:
- 表格
- 阻止
- 行
- 单元格
- 字段
根元素是Form
。
在From
内部放置Block
。
Block
包含一些 Rows
,每个 Row
可以包含一些 Cell
,其中包含不同的内容: Field
或 Block
,其中 Block
又是嵌套结构 Block -> Rows -> Cells -> Field/Block
。
它是一个有向有限图,从根Form
开始,结束顶点Field
或Block
。
只有Block
和Field
实体具有返回顶点id的方法getId()
。基于此,我构建了从根到具体顶点的路径(Blcok,Field)
。
我尝试检查具体顶点实体( block )
是否按路径呈现在图中,所以我的解决方案是:
- 从起点设置当前顶点(Block),设置顶点的收入路径
- 循环获取当前顶点( block )的所有行
- 然后在第一个循环中使用循环获取每行的所有单元格
- 然后从每个单元格(字段、 block )获取内容
- 检查它是否为 Block,然后获取其
id
并与传入路径(id)进行比较 - 如果不相等,则将找到的 block 设置为当前 block (for 循环)
- 继续,直到找不到路径
代码是:
function getBlockFieldByPath(block: Block, path: string) {
let currentBlock = block;
let irows = 0;
let jcells = 0;
while(irows < currentblock.getRows().length) {
let cells = rows[irows].getCells();
while(jcells < cells.length) {
let content = cells[jcells].getContent(); // it is should be Block or Field,
if (content.getId() == path) {
return content;
}
if (content == Block) {
currentblock = content; // Because content is Block
}
jcells++;
}
irows++;
}
}
我的错误在哪里?
最佳答案
通过一些抽象,您可以得到一个图,其中节点是 block 。
其中一些是平凡的叶子。
您只想对图表进行 dfs,直到找到与您的路径字符串匹配的 block
function dfs(block, path) {
if (block.getId() === path) return block
let found = null
block.getRows().find(r => r.getCells().find(bContent => {
let b = bContent.getContent()
found = dfs(b, path)
return found
}))
return found
}
<小时/>
堆栈的变化
function dfs(block, path) {
const stack = [block]
while (stack.length) {
const b = stack.pop()
if (b.getId() === path) return block
b.getRows().forEach(r => r.getCells().forEach(bContent => {
let b = bContent.getContent()
stack.push(b)
})
}
return null
}
关于javascript - 如何找到图中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60899471/