Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Program to check words can be found in matrix character board or not in Python
Suppose we have a matrix character board. Where each cell is holding a character. We also have a string called target, we have to check whether the target can be found in the matrix by going left-to-right, or up-to-down unidirectional way, or not.
So, if the input is like
| a | n | t | s |
| s | p | i | n |
| l | a | p | s |
Word = “tip”
then the output will be True, you can see the third column (top to bottom) is forming "tip".
To solve this, we will follow these steps −
- for each i in board, do
- i := make word from characters present in i
- if word is present in i, then
- return True
- i := 0
- while i < row count of board, do
- j := make string from the characters of ith column in board
- i := i + 1
- if word is in j, then
- return True
- return False
Example
Let us see the following implementation to get better understanding −
def solve(board, word): for i in board: i = "".join(i) if word in i: return True i = 0 while i < len(board): j = "".join([col[i] for col in board]) i += 1 if word in j: return True return False board = [["a","n","t","s"],["s","p","i","n"],["l","a","p","s"]] word = "tip" print(solve(board, word))
Input
[["a","n","t","s"], ["s","p","i","n"], ["l","a","p","s"]], "tip"
Output
True
Advertisements
