📌  相关文章
📜  查找矩阵中给定单词的所有出现

📅  最后修改于: 2021-04-29 14:58:46             🧑  作者: Mango

给定字符和单词的2D网格,找到网格中给定单词的所有出现。一个单词可以在所有8个方向上的任意点匹配。如果所有字符在该方向上匹配,则表示在该方向上找到单词(不是锯齿形)。

如果找到一个循环,该解决方案应打印所有坐标。 IE

这8个方向分别是:水平左,水平右,垂直向上,垂直向下和4个对角线。

Input:
mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'},
                  {'H', 'E', 'D', 'E', 'S'},
             {'S', 'G', 'N', 'D', 'E'}
               };
Word = “DES”
Output:
D(1, 2) E(1, 1) S(2, 0) 
D(1, 2) E(1, 3) S(0, 4) 
D(1, 2) E(1, 3) S(1, 4)
D(2, 3) E(1, 3) S(0, 4)
D(2, 3) E(1, 3) S(1, 4)
D(2, 3) E(2, 4) S(1, 4)

Input:
char mat[ROW][COL] = { {'B', 'N', 'E', 'Y', 'S'},
                       {'H', 'E', 'D', 'E', 'S'},
                       {'S', 'G', 'N', 'D', 'E'}};
char word[] ="BNEGSHBN";
Output:
B(0, 0) N(0, 1) E(1, 1) G(2, 1) S(2, 0) H(1, 0)
                               B(0, 0) N(0, 1) 

查找给定单词的所有出现
强烈建议您最小化浏览器,然后自己尝试。
这主要是这篇文章的扩展。此处还会打印位置路径。

通过在矩阵中单词的第一个字符的每次出现上应用DFS()可以轻松解决该问题。 2D矩阵中的一个单元可以连接到8个邻居。因此,与标准DFS()不同,在该标准中我们递归地调用所有相邻的顶点,而在这里我们只能递归地调用8个邻居。

CPP
// Program to find all occurrences of the word in
// a matrix
#include 
using namespace std;
  
#define ROW 3
#define COL 5
  
// check whether given cell (row, col) is a valid
// cell or not.
bool isvalid(int row, int col, int prevRow, int prevCol)
{
    // return true if row number and column number
    // is in range
    return (row >= 0) && (row < ROW) &&
           (col >= 0) && (col < COL) &&
           !(row== prevRow && col == prevCol);
}
  
// These arrays are used to get row and column
// numbers of 8 neighboursof a given cell
int rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1};
  
// A utility function to do DFS for a 2D boolean
// matrix. It only considers the 8 neighbours as
// adjacent vertices
void DFS(char mat[][COL], int row, int col,
         int prevRow, int prevCol, char* word,
         string path, int index, int n)
{
    // return if current character doesn't match with
    // the next character in the word
    if (index > n || mat[row][col] != word[index])
        return;
  
    //append current character position to path
    path += string(1, word[index]) + "(" + to_string(row)
            + ", " + to_string(col) + ") ";
  
    // current character matches with the last character
    // in the word
    if (index == n)
    {
        cout << path << endl;
        return;
    }
  
    // Recur for all connected neighbours
    for (int k = 0; k < 8; ++k)
        if (isvalid(row + rowNum[k], col + colNum[k],
                    prevRow, prevCol))
  
            DFS(mat, row + rowNum[k], col + colNum[k],
                row, col, word, path, index+1, n);
}
  
// The main function to find all occurrences of the
// word in a matrix
void findWords(char mat[][COL], char* word, int n)
{
    // traverse through the all cells of given matrix
    for (int i = 0; i < ROW; ++i)
        for (int j = 0; j < COL; ++j)
  
            // occurrence of first character in matrix
            if (mat[i][j] == word[0])
  
                // check and print if path exists
                DFS(mat, i, j, -1, -1, word, "", 0, n);
}
  
// Driver program to test above function
int main()
{
    char mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'},
                          {'H', 'E', 'D', 'E', 'S'},
                          {'S', 'G', 'N', 'D', 'E'}
                        };
  
    char word[] ="DES";
  
    findWords(mat, word, strlen(word) - 1);
  
    return 0;
}


Java
// Java Program to find all occurrences of the word in
// a matrix
import java.util.*;
  
class GFG
{
  
static final int ROW = 3;
static final int COL = 5;
  
// check whether given cell (row, col) is a valid
// cell or not.
static boolean isvalid(int row, int col, int prevRow, int prevCol)
{
    // return true if row number and column number
    // is in range
    return (row >= 0) && (row < ROW) &&
        (col >= 0) && (col < COL) &&
        !(row == prevRow && col == prevCol);
}
  
// These arrays are used to get row and column
// numbers of 8 neighboursof a given cell
static int rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1};
static int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1};
  
// A utility function to do DFS for a 2D boolean
// matrix. It only considers the 8 neighbours as
// adjacent vertices
static void DFS(char mat[][], int row, int col,
        int prevRow, int prevCol, char[] word,
        String path, int index, int n)
{
    // return if current character doesn't match with
    // the next character in the word
    if (index > n || mat[row][col] != word[index])
        return;
  
    // append current character position to path
    path += (word[index]) + "(" + String.valueOf(row)
            + ", " + String.valueOf(col) + ") ";
  
    // current character matches with the last character
    // in the word
    if (index == n)
    {
        System.out.print(path +"\n");
        return;
    }
  
    // Recur for all connected neighbours
    for (int k = 0; k < 8; ++k)
        if (isvalid(row + rowNum[k], col + colNum[k],
                    prevRow, prevCol))
  
            DFS(mat, row + rowNum[k], col + colNum[k],
                row, col, word, path, index + 1, n);
}
  
// The main function to find all occurrences of the
// word in a matrix
static void findWords(char mat[][], char []word, int n)
{
    // traverse through the all cells of given matrix
    for (int i = 0; i < ROW; ++i)
        for (int j = 0; j < COL; ++j)
  
            // occurrence of first character in matrix
            if (mat[i][j] == word[0])
  
                // check and print if path exists
                DFS(mat, i, j, -1, -1, word, "", 0, n);
}
  
// Driver code
public static void main(String[] args)
{
    char mat[][]= { {'B', 'N', 'E', 'Y', 'S'},
                    {'H', 'E', 'D', 'E', 'S'},
                    {'S', 'G', 'N', 'D', 'E'}};
  
    char []word ="DES".toCharArray();
  
    findWords(mat, word, word.length - 1);
}
}
  
// This code is contributed by PrinciRaj1992


Python3
# Python3 Program to find all occurrences of the word in
# a matrix
ROW = 3
COL = 5
  
# check whether given cell (row, col) is a valid
# cell or not.
def isvalid(row, col, prevRow, prevCol):
      
    # return true if row number and column number
    # is in range
    return (row >= 0) and (row < ROW) and (col >= 0) and \
           (col < COL) and not (row== prevRow and col == prevCol)
  
# These arrays are used to get row and column
# numbers of 8 neighboursof a given cell
rowNum = [-1, -1, -1, 0, 0, 1, 1, 1]
colNum = [-1, 0, 1, -1, 1, -1, 0, 1]
  
# A utility function to do DFS for a 2D boolean
# matrix. It only considers the 8 neighbours as
# adjacent vertices
def DFS(mat, row, col,prevRow, prevCol, word,path, index, n):
      
    # return if current character doesn't match with
    # the next character in the word
    if (index > n or mat[row][col] != word[index]):
        return
      
    # append current character position to path
    path += word[index] + "(" + str(row)+ ", " + str(col) + ") "
      
    # current character matches with the last character\
    # in the word
    if (index == n):
        print(path)
        return
      
    # Recur for all connected neighbours
    for k in range(8):
        if (isvalid(row + rowNum[k], col + colNum[k],prevRow, prevCol)):
            DFS(mat, row + rowNum[k], col + colNum[k],row, col, word, path, index + 1, n)
  
# The main function to find all occurrences of the
# word in a matrix
def findWords(mat,word, n):
      
    # traverse through the all cells of given matrix
    for i in range(ROW):
        for j in range(COL):
              
            # occurrence of first character in matrix
            if (mat[i][j] == word[0]):
                # check and prif path exists
                DFS(mat, i, j, -1, -1, word, "", 0, n)
  
# Driver code
mat = [['B', 'N', 'E', 'Y', 'S'],
        ['H', 'E', 'D', 'E', 'S'],
        ['S', 'G', 'N', 'D', 'E']]
word = list("DES")
findWords(mat, word, len(word) - 1)
      
# This code is contributed by SHUBHAMSINGH10


C#
// C# Program to find all occurrences of the word in
// a matrix
using System;
  
class GFG
{
  
static readonly int ROW = 3;
static readonly int COL = 5;
  
// check whether given cell (row, col) is a valid
// cell or not.
static bool isvalid(int row, int col, int prevRow, int prevCol)
{
    // return true if row number and column number
    // is in range
    return (row >= 0) && (row < ROW) &&
        (col >= 0) && (col < COL) &&
        !(row == prevRow && col == prevCol);
}
  
// These arrays are used to get row and column
// numbers of 8 neighboursof a given cell
static int []rowNum = {-1, -1, -1, 0, 0, 1, 1, 1};
static int []colNum = {-1, 0, 1, -1, 1, -1, 0, 1};
  
// A utility function to do DFS for a 2D bool
// matrix. It only considers the 8 neighbours as
// adjacent vertices
static void DFS(char [,]mat, int row, int col,
        int prevRow, int prevCol, char[] word,
        String path, int index, int n)
{
    // return if current character doesn't match with
    // the next character in the word
    if (index > n || mat[row,col] != word[index])
        return;
  
    // append current character position to path
    path += (word[index]) + "(" + String.Join("",row)
            + ", " + String.Join("",col) + ") ";
  
    // current character matches with the last character
    // in the word
    if (index == n)
    {
        Console.Write(path +"\n");
        return;
    }
  
    // Recur for all connected neighbours
    for (int k = 0; k < 8; ++k)
        if (isvalid(row + rowNum[k], col + colNum[k],
                    prevRow, prevCol))
  
            DFS(mat, row + rowNum[k], col + colNum[k],
                row, col, word, path, index + 1, n);
}
  
// The main function to find all occurrences of the
// word in a matrix
static void findWords(char [,]mat, char []word, int n)
{
    // traverse through the all cells of given matrix
    for (int i = 0; i < ROW; ++i)
        for (int j = 0; j < COL; ++j)
  
            // occurrence of first character in matrix
            if (mat[i,j] == word[0])
  
                // check and print if path exists
                DFS(mat, i, j, -1, -1, word, "", 0, n);
}
  
// Driver code
public static void Main(String[] args)
{
    char [,]mat= { {'B', 'N', 'E', 'Y', 'S'},
                    {'H', 'E', 'D', 'E', 'S'},
                    {'S', 'G', 'N', 'D', 'E'}};
  
    char []word ="DES".ToCharArray();
  
    findWords(mat, word, word.Length - 1);
}
}
  
// This code is contributed by 29AjayKumar


输出 :

D(1, 2) E(1, 1) S(2, 0) 
D(1, 2) E(1, 3) S(0, 4) 
D(1, 2) E(1, 3) S(1, 4) 
D(2, 3) E(1, 3) S(0, 4) 
D(2, 3) E(1, 3) S(1, 4) 
D(2, 3) E(2, 4) S(1, 4)