algorithm - 技术面试 : Longest Non-Decreasing Subsequence in MxN Matrix

标签 algorithm

<分区>

我最近在一次技术面试中被问到这个问题。这是我的解决方案。 http://pastebin.com/JMVHcfRq是我弄错了还是有更好的解决方案?

Find the length of the longest non-decreasing sequence through adjacent, non-repeating cells (including diagonals) in a rectangular grid of numbers in a language of your choice. The solution should handle grids of arbitrary width and height.
For example, in the following grid, one legal path (though not the longest) that could be traced is 0->3->7->9 and its length would be 4.
8 2 4
0 7 1
3 7 9
The path can only connect adjacent locations (you could not connect 8 -> 9). The longest possible sequence for this example would be of length 6 by tracing the path 0->2->4->7->7->9 or 1->2->4->7->7->8.
Write a method, in a language of your choice, that takes a rectangular grid of numbers as input, and returns the length of the longest such sequence as output.

最佳答案

您可以使用有向图为您的问题建模:

每个单元格都是图中的顶点,如果两个单元格 Ci,j,Ck,m 相邻且 Ci,j < Ck,m.

现在你的问题是在这个图中找到最长的路径,但这个图是有向无环图,因为正如问题所说,矩阵中没有重复的数字,“<”关系也是反对称的。所以你的问题减少到在有向无环图中找到最长的路径,这很容易通过首先进行拓扑排序然后找到最长的路径。例如参见 this .

更新: 乍一看,我认为不可能有相等的邻居,但现在我看到是可能的,在上面的图形构造中,我们应该将 < 替换为 <= 然后确保图形不是无环的,但问题仍然是找到该图中的最长路径。

P.S1:如果我有这个最长路径问题的任何多项式答案,我会把它带到这里,但可能通过这种问题分类更容易搜索它。

P.S2:如mbeckish在评论中提到,longest path problem在一般图中是NP-Hard,但我认为在这种特殊情况下可以在P中解决,但我现在没有确切的算法。

P.S3:我做了一点研究,我看到,Hamiltonian path in grid graph is NP-Complete ,看来您的问题也是 NP-Complete(我现在没有减少,但它们彼此非常接近)。

关于algorithm - 技术面试 : Longest Non-Decreasing Subsequence in MxN Matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15553218/

相关文章:

javaFX:错误的合并排序动画结果

algorithm - 如何将 RGB 颜色转换为最接近匹配的 8 位颜色?

javascript - PIL 逊相关函数返回 Nan

python - 即使使用队列也无法按广度搜索

java - 采访Q : Finding mode of array

c - 如何在 openmp 中并行化 while 循环 - 共轭梯度

java - 将链表拆分为 2 个包含最小和最大数字的偶数列表

algorithm - 插入 BST 时,插入的第一项是否总是树的根?

c# - Word 如何在高级搜索中找到匹配的词形?

performance - 排序算法的内存速度权衡