【问题标题】:Finding the set of all winning tic tac toe board states找到所有获胜的井字棋棋盘状态的集合
【发布时间】:2017-09-20 16:39:45
【问题描述】:

这是我的问题。我想创建一个算法,它为 n 维井字棋盘生成每个可能的获胜棋盘状态的数组数组。假设您有一个 n = 2 的板,即 2x2,那么该函数应返回以下数组:

wins = [
    [1,2],
    [1,3],
    [1,4],
    [2,4]
]

我知道这并不是一个 MATLAB 问题,但我正在努力扩展我对 MATLAB 工作原理的理解。我的总体想法是一种执行以下操作的算法:

generate an n-dimensional board of zeros
1. Go to the first cell, record that index ([1,])
2. Go to the end of the row, and that's your first board state ([1,2])
3. Go to the end of the column, that's your second board state ([1,3])
4. Go to the end of the diagonal, that's your third board state ([2,3])
5. Advance to the next cell, repeat, checking if you have already created that board state first ([2,4] should be the only one it hasn't done)

我想我想多了这个问题,但我不知道如何解决它。有人可以给我一些指导如何以 MATLAB-y 的方式做到这一点吗?我的猜测是遍历矩阵并只选择整行/列/对角线很容易,这是我没有得到的“检查它是否存在”部分。一般来说,你会如何称呼这个算法?感谢您的帮助!

【问题讨论】:

    标签: arrays algorithm matlab


    【解决方案1】:

    更好的主意:您不要按方格进行,而是按维度进行。对于板上的每个维度,您可以通过获胜组合使坐标发生变化或不发生变化:

    • 遍历所有可能的值,从低到高
    • 遍历所有可能的值,从高到低
    • 在其他维度迭代时保持不变,但对范围内的每个值都这样做,对其他坐标重复。

    例如,对于一个 4^3 的棋盘,让我们看看最后一个坐标(称它们为 x1、x2、x3),x3。假设您已经确定 x1 将从低到高迭代,x2 恒定为 2。您现在将 x3 处理为:

    • 遍历所有可能的值,从低到高
      • (1, 2, 1), (2, 2, 2), (3, 2, 3)
    • 遍历所有可能的值,从高到低
      • (1, 2, 3), (2, 2, 2), (3, 2, 1)
    • 在其他维度迭代时保持不变,但对范围内的每个值都这样做,对其他坐标重复。
      • (1, 2, 1), (2, 2, 1), (3, 2, 1)
      • (1, 2, 2), (2, 2, 2), (3, 2, 2)
      • (1, 2, 3), (2, 2, 3), (3, 2, 3)

    这会让你感动吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 2020-03-23
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多