这是一种方法:
%// Example word grid
C = [
'a' 'h' 'c' 'k' 'r'
'x' 'r' 'j' 'i' 'p'
'b' 'v' 't' 'l' 'q'
'a' 'y' 'q' 's' 'o'];
%// Your search term
target = 'arts';
%// Optionally, do some obvious checks here.
%// - length of the search string may exceeds the grid's dimensions
%// - there are no matches for the first letter
%// - and similar
%// Form single cellstring containing all search directions
allDirections = [
%{
// horizontal, horizontal-reversed
%}
cellstr([C ; C(:,end:-1:1)])
%{
// vertical, vertical-reversed
%}
cellstr([C'; C(:,end:-1:1)'])
%{
// Diagonal, top-left to bottom-right, and reversed
%}
arrayfun(@(ii){diag(C,ii)'}, -size(C,1)+2:size(C,2)-2)';
arrayfun(@(ii){diag(C(end:-1:1,end:-1:1),ii)'}, -size(C,1)+2:size(C,2)-2)';
%{
// Diagonal, top-right to bottom-left, and reversed
%}
arrayfun(@(ii){diag(C(:,end:-1:1),ii)'}, -size(C,1)+2:size(C,2)-2)';
arrayfun(@(ii){diag(C(end:-1:1,:),ii)'}, -size(C,1)+2:size(C,2)-2)';
];
%// And now just find the string
strfind(allDirections , target)
当然,你可以通过
来提高(内存)效率
- 分别在所有方向上执行
strfind
- 在同一方向上执行 2 ×
strfind,但 target 倒置
- 等。
但除了这些相对较小的优化之外,我认为您在 MATLAB在实践中可以做得更好。
理论上更有效的递归、分支定界类型搜索大致如下:
- 查找第一个字母的所有匹配项
- 根据网格的尺寸消除所有不能满足
target 长度的匹配项
- 在所有匹配项的邻域中搜索第二个字母的出现次数
- 根据长度等消除出现次数。
(不要忘记在第二个字母之后过滤 direction,因为第二个字母的命中会确定搜索方向)
据我所知,与我的版本相比,这需要更少的读取和比较。但是,我的猜测是使用固定例程(就像我所做的那样)会比使用(嵌套)循环更快且更简单。但我可能是错的。
试试看。轮廓。学习。微笑。纠正我:)