Since you do not define the preferred language that I implemented in C #:
private static readonly int[] dx = new int[] { 1, 1, 1, 0, 0, -1, -1, -1 }; private static readonly int[] dy = new int[] { -1, 0, 1, 1, -1, -1, 0, 1 }; private static List<string> words; private static List<string> GetAllWords(char[,] matrix ,int d) { words = new List<string>(); bool[,] visited = new bool[4, 4]; char[] result = new char[d]; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) Go(matrix, result, visited, d, i, j); return words; } private static void Go(char[,] matrix, char[] result, bool[,] visited, int d, int x, int y) { if (x < 0 || x >= 4 || y < 0 || y >= 4 || visited[x, y]) return; if (d == 0) { words.Add(new String(result)); return; } visited[x, y] = true; result[d - 1] = matrix[x, y]; for (int i = 0; i < 8; i++) { Go(matrix, result, visited, d - 1, x + dx[i], y + dy[i]); } visited[x, y] = false; }
Code to get the results:
char[,] matrix = new char[,] { { 'A', 'B', 'C', 'D' }, { 'U', 'A', 'L', 'E' }, { 'T', 'S', 'U', 'G' }, { 'N', 'E', 'Y', 'I' } }; List<string> list = GetAllWords(matrix, 3);
Change parameter 3 to the desired text length.