一種算法想到馬上,雖然優化可以進行,如果時間複雜性是一個問題。
在2x2陣列中的每個元素(或者我們可以稱它爲矩陣,如果你喜歡的話),我們可以在8個方向行進(北,東,東,南,西,西,西北)。
對算法的肉僞代碼都有點像這樣(我假設按值傳遞,讓「current_string」是在每個函數調用一個新的字符串):
find(position, direction, current_string){
new_letter = m[0, position + direction];
if(!current_string.Contains(new_letter)){
// We have not yet encountered this letter during the search.
// If letters occur more than once in the array, then you must
// assign an index to each position in the array instead and
// store which positions have been encountered along each
// search path instead.
current_string += new_letter;
find(position, (0, 1), current_string);
find(position, (1, 1), current_string);
find(position, (1, 0), current_string);
find(position, (1, -1), current_string);
find(position, (0, -1), current_string);
find(position, (-1, -1), current_string);
find(position, (-1, 0), current_string);
find(position, (-1, 1), current_string);
} else {
// This letter has been encountered during this path search,
// terminate this path search. See comment above if letters
// occur more than once in the matrix.
print current_string; // Print one of the found strings!
}
}
現在,您需要爲諸如「位置+方向超出數組邊界之外的東西」添加一些檢查,如果是,則打印current_string並終止。
上述算法的高層次思想是遞歸地搜索所有可能的路徑,當它們跑進它們自己時終止路徑(以與遊戲Snake中的蛇相同的方式)。
如果您使用哈希來測試對當前字符串(根據行if(!current_string.Contains(new_letter)){
)(這是分段O(1)搜索)的新字母的包含,則該算法的最壞情況運行時複雜度在數量上是線性的矩陣中有可能的字符串。即如果矩陣中有n個可能的字符串組合,那麼這個算法需要大約n個步驟才能完成,其中c是一個常數。
是「組合」矩陣中元素的有序序列,還是僅僅是矩陣中的一組元素? – 2011-02-01 02:59:22