
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Words Generated from Matrix of Letters in Python
Suppose we have a 4 x 4 board of letters and a list of words, we have to find the largest number of words that can be generated in the board by a sequence of adjacent letters, using one cell at most once per word (but we can reuse cells for other words). We can go up, down, left, right, or diagonal direction.
So, if the input is like
m | b | f | d |
x | a | y | a |
t | z | t | r |
s | q | q | q |
words = ["bat", "far", "mat"], then the output will be 3, as we can generate mat [0,1] → [1,1] → [2,0], bat [0,2] → [1,1] → [2,2], and far [0,2] → [1,3] → [2,3].
To solve this, we will follow these steps −
N := row count of A, M := column count of size of A
trie := a new map
-
for each word in words, do
current := trie
-
for each c in word, do
-
if c is in current, then
current := current[c]
-
otherwise,
current[c] := a new map
current := current[c]
-
current["*"] := True
ans := 0
Define a function dfs() . This will take x, y, d
-
if "*" is in d, then
remove d["*"]
ans := ans + 1
temp := A[x, y]
A[x, y] := "#"
-
for each item i in [x - 1, x, x + 1], do
-
for each item j in [y - 1, y, y + 1], do
-
if i and j in range of matrix and A[i, j] is in d, then
dfs(i, j, d[A[i, j]])
-
-
A[x, y] := temp
From the main method do the following −
-
for i in range 0 to N, do
-
for j in range 0 to M, do
-
if A[i][j] is in trie, then
dfs(i, j, trie[A[i, j]])
-
-
return ans
Example (Python)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, A, words): N = len(A) M = len(A[0]) trie = dict() for word in words: current = trie for c in word: if c in current: current = current[c] else: current[c] = dict() current = current[c] current["*"] = True ans = 0 def dfs(x, y, d): nonlocal ans if "*" in d: del d["*"] ans += 1 temp = A[x][y] A[x][y] = "#" for i in [x - 1, x, x + 1]: for j in [y - 1, y, y + 1]: if 0 <= i < N and 0 <= j < M and A[i][j] in d: dfs(i, j, d[A[i][j]]) A[x][y] = temp for i in range(N): for j in range(M): if A[i][j] in trie: dfs(i, j, trie[A[i][j]]) return ans ob = Solution() matrix = [ ["m", "b", "f", "d"], ["x", "a", "y", "a"], ["t", "z", "t", "r"], ["s", "q", "q", "q"] ] words = ["bat", "far", "mat"] print(ob.solve(matrix, words))
Input
[ ["m", "b", "f", "d"], ["x", "a", "y", "a"], ["t", "z", "t", "r"], ["s", "q", "q", "q"] ], ["bat", "far", "mat"]
Output
3