c# - 具有 5 个字符的 4x4 矩阵的所有组合

标签 c# .net algorithm combinations

我有一个像这样的矩阵:

0 | 1 | 2 | 3
-------------
7 | 6 | 5 | 4
-------------
8 | 9 | A | B
-------------
F | E | D | C

在代码中:

var matrix = new char[][]
{ 
    new char[] { '0', '1', '2', '3' },
    new char[] { '7', '6', '5', '4' },
    new char[] { '8', '9', 'A', 'B' },
    new char[] { 'F', 'E', 'D', 'C' }
};

我需要得到这个矩阵的所有可能组合,每个有 5 个字符,但每个字符必须是下一个直接邻居,例如,0,5 和 4,8 无效,但 0,6 和 3,4 有效.

这个矩阵不会像示例中那样是静态的,它每次都在任意位置生成十六进制数。

谢谢!

最佳答案

只是为了好玩 - Delphi 代码。 'shl' 是左移 (<<),字符串是从一开始的。在矩阵周围添加边框作为哨兵以简化检查。

一些附加评论:我使用 6x6 矩阵 - 4x4 核心带数字,外边框为一个单元格宽度。 Int64 的 36 位用作哨兵。位值为 1 表示边界或访问单元格。程序 StartTravel 从核心的某个起始单元开始路径查找。路径查找类似于 DFS(深度优先搜索),但当路径长度变为 5 时中断。

const
  Directions: array[0..3] of Integer = (-1, -6, 1, 6);

var
  Digits: string;
  Mask: Int64;
  i, j: Integer;

  procedure Travel(AFrom: Integer; Visited: Int64; Path: string);
  var
    i, Dir: Integer;
    NewMask: Int64;
  begin
    if Length(Path) = 5 then
      PrintOut(Path)
    else
      for i := 0 to 3 do begin
        Dir := Directions[i];
        NewMask := 1 shl (AFrom + Dir);
        if (Visited and NewMask) = 0 then
          Travel(AFrom + Dir, Visited or NewMask, Path + Digits[AFrom + Dir + 1]);
      end;
  end;

  procedure Init;
  var
    i: Integer;
  begin
    Digits := '-------0123--7654--89AB--FEDC-------';
    Mask := 0;
    for i := 1 to Length(Digits) do
      if Digits[i] = '-' then
        Mask := Mask or (1 shl (i - 1));
  end;

  procedure StartTravel(Row, Col: Integer);
  var
    APos: Integer;
  begin
    APos := Row * 6 + Col + 7;
    Travel(APos, Mask or (1 shl APos), Digits[APos + 1]);
  end;

begin
  Init;
  for i := 0 to 3 do
    for j := 0 to 3 do
      StartTravel(i, j);

432 combinations:
01234
01256
01254
0125A
01678
01652
01654
0165A
01698
0169A
0169E
07612
07652
....
CBADE
CB456
CB452
CB45A
CB432

关于c# - 具有 5 个字符的 4x4 矩阵的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8310157/

相关文章:

java - 我在网上找到的一个有趣的谷歌面试算法,需要线性时间

java - 为什么迭代列表给我 stackoverflow 错误?

c# - LogicalTreeHelper.GetChildren - ObservableCollection Move() 导致 DataTemplate 中的 ContentControl 丢失其内容?

c# - 在 TCP 连接中使用安全性

.net - 如何在 .NET 中序列化此 Xml(数组)

c# - 在 Windows 中创建一个临时目录?

c# - 开源 C# 代理服务器 - 任何项目/示例?

objective-c - 如何在 Objective-C 中检测图像中的 body ?

c# - 如何在 ControlRemoved 事件发生后获取刷新的 TabPages 列表?

c# - 通过单击更改 MySQL 中的 listBox 内容