编程难题:如何画板?

时间:2012-04-28 14:06:58

标签: algorithm language-agnostic puzzle

我们应该绘制一个N x M板。我们可以一次绘制整行或整列。给定所有电路板单元的N x M颜色矩阵,找到绘制电路板的最少数量的绘制操作。

例如:我们应该按如下方式绘制一个3 x 3的板(R - 红色,B - 蓝色,G - 绿色):

B,B,B
B,R,R
B,G,G

最少的绘画操作是4:

  • 用蓝色
  • 绘制第0行
  • 用红色
  • 绘制第1行
  • 用绿色
  • 绘制第2行
  • 使用Blue
  • 绘制列0

你会如何解决它?

2 个答案:

答案 0 :(得分:6)

这看起来很有趣。让我用一些伪代码拍摄它。

Function MinPaints(Matrix) Returns Integer
    If the matrix is empty return 0
    Find all rows and columns which have a single color
    If there are none, return infinity, since there is no solution
    Set the current minimum to infinity
    For each row or column with single color:
        Remove the row/column from the matrix
        Call MinPaints with the new matrix
        If the result is less than the current minimum, set the current minimum to the result
    End loop
    Return the current minimum + 1
End Function

我认为这将解决您的问题,但我没有尝试任何优化或任何事情。这可能不够快,我不知道。我怀疑这个问题在亚指数时间内是可以解决的。

以下是此算法如何解决该示例:

BBB
BRR
BGG
|
+---BRR
|   BGG
|   |
|   +---RR
|   |   GG
|   |   |
|   |   +---GG
|   |   |   |
|   |   |   +---[]
|   |   |   |   |
|   |   |   |   Solvable in 0
|   |   |   |
|   |   |   Solvable in 1
|   |   |
|   |   +---RR
|   |   |   |
|   |   |   +---[]
|   |   |   |   |
|   |   |   |   Solvable in 0
|   |   |   |
|   |   |   Solvable in 1
|   |   |
|   |   Solvable in 2
|   |
|   Solvable in 3
|                       BB
+---Another branch with RR ...
|                       GG
Solvable in 4

答案 1 :(得分:3)

对于初学者,您可以尝试明确的详尽搜索

让您的状态图表为:G=(V,E)其中V = {all possible boards}E = {(u,v) | you can move from board u to v within a single operation}

  • 请注意,您不需要提前生成图表 - 您可以使用successors(board)函数动态生成图表,该函数将返回给定电路板的所有后继函数。

您还需要h:V->R - admissible heuristic function来评估董事会 1

现在,您可以运行A*bi-directional BFS搜索[或两者的组合],您的来源将是白板,您的目标是请求的主板。因为我们使用可接受的启发式函数--A *既是complete(总是找到解决方案,如果存在)和optimal(找到最短的解决方案),它将找到最佳解决方案。 [同样适用于双向BFS]。

<强>缺点:

  • 虽然通知算法,但它会有指数行为。 但如果是面试问题,我认为是非效率的 解决方案比没有解决方案好。
  • 虽然完整且最优 - 如果没有解决方案 - 算法可能会陷入无限循环,或者至少是一个非常长的循环,直到它意识到它已经超越了所有可能性。

(1)允许启发式的示例是h(board) = #(miscolored_squares)/max{m,n}

相关问题