假设我有3个单词:[“ mouse”,“ fish”,“ cat”]
和一个4x3的矩阵
[][][][]
[][][][]
[][][][]
我需要使用2条简单规则将这些单词改组为矩阵:
例如一个很好的组合(使用上面的3个词):
[C][F][I][M]
[A][H][S][O]
[T][E][S][U]
什么是实现此目标的正确算法? 我尝试自己写它,但是以半数有效的算法结束
void Main(){
string[,] letterGrid = new string[4,3];
//initialize array
for (int i = 0; i < letterGrid.GetLength(1); i++)
{
for (int t = 0; t < letterGrid.GetLength(0); t++)
{
letterGrid[t, i] = "-1";
}
}
string[,] validateGrid = (string[,])letterGrid.Clone();
string[] words = ["mouse","fish","cat"];
Random rnd = new Random();
//prepare grid
foreach (string word in words)
{
int rndx = rnd.Next(0, letterGrid.GetLength(0));
int rndy = rnd.Next(0, letterGrid.GetLength(1));
letterGrid = GetModifiedGrid((string[,])letterGrid.Clone(), word, rndx, rndy, new List<char> { },
(string[,])validateGrid.Clone(), new int[] { -1, -1});
}
}
//letterGrid & validate starts as a same matrix consists of -1's
//validate matrix simply marks which cells the function already 'visited'
string[,] GetModifiedGrid(string[,] letterGrid, string word, int x, int y, List<char> chars, string[,] validate, int[] lastPos)
{
var tempLetterGrid = letterGrid;
var tempValidate = validate;
if (chars.Count == word.Length)
{
return tempLetterGrid;
}
else if(tempValidate[x, y] != word[chars.Count].ToString()) {
tempValidate[x, y] = word[chars.Count].ToString();
if (tempLetterGrid[x, y] == "-1" && (lastPos[0] == -1 || ((x == lastPos[0] && Mathf.Abs(y - lastPos[1]) < 2) || (y ==
lastPos[1] && Mathf.Abs(x - lastPos[0]) < 2))))
{
lastPos[0] = x; lastPos[1] = y;
tempLetterGrid[x, y] = word[chars.Count].ToString();
chars.Add(word[chars.Count]);
}
if(x + 1 < tempLetterGrid.GetLength(0))
GetModifiedGrid(tempLetterGrid, word, x + 1, y, chars, tempValidate, lastPos);
if (y + 1 < tempLetterGrid.GetLength(1))
GetModifiedGrid(tempLetterGrid, word, x, y + 1, chars, tempValidate, lastPos);
if (x - 1 >= 0)
GetModifiedGrid(tempLetterGrid, word, x - 1, y, chars, tempValidate, lastPos);
if (y - 1 >= 0)
GetModifiedGrid(tempLetterGrid, word, x, y - 1, chars, tempValidate, lastPos);
}
return tempLetterGrid;
}
希望有人能够提供帮助, 谢谢。