Given a matrix of size N*N. We need to find out number of locations of particular string

时间:2015-07-16 11:44:44

标签: c++ algorithm recursion backtracking

As the title of question suggests that we have to find the number of occurences of particular string in a grid of characters of size N(<=1000). We can only go diagonally. For Example

  5               //N
  B X A X X       //grid
  X A X X X       
  X B B X X
  X A X A X
  X X B X X
  ABA           //Finding its occurence in the above grid 

  Answer is 14 

I don't know how to solve this question. I have seen people doing this with some kind of recursion (they say it's backtracking).

What I have done till now

I tried to solve this using BFS and it gives right answer for small cases but not giving anything for large N.

My code for BFS that I have tried

#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define nline puts("\n")
vector<pair<int,int> >v;
#define e .00000001
string s;
char ch[1000][1000];
int dx[4] = {1, 1, -1, -1};
int dy[4] = { -1, 1, 1, -1 };
char vis[1000][1000];
int n,total=0;
struct data
{
    int x,y;
    void set(int _x,int _y)
    {
        x=_x;
        y=_y;
    }
};

void bfs(data src)
{
    vis[src.x][src.y]=true;
    queue<data>Q;
    Q.push(src);
    int len=1;
    while(not Q.empty())
    {
        data ss=Q.front();
        Q.pop();
        for(int i=0;i<4;i++)
        {
            int xx=dx[i]+ss.x;
            int yy=dy[i]+ss.y;
            if(len<=s.length()-1 and ch[xx][yy]==s[len] and xx>=0 and xx<n and yy>=0 and yy<n and (not vis[xx][yy]))
            {
                vis[xx][yy]=true;
                data tem;
                tem.set(xx,yy);
                Q.push(tem);
                len++;
            }
        }
    }
      if(len==s.length())total++;
}
int main() {
    cin>>n;
    for(int i=0;i<n;i++)
    for(int j=0;j<n;j++)
    cin>>ch[i][j];
   cin>>s;
   for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
       {
           if(ch[i][j]==s[0])
          {
               data start;
               start.set(i,j);
               bfs(start);
               memset(vis,0,sizeof vis);
          }
       }
    }
      cout<<total<<endl;
      return 0;
}

Can anyone help me out? :)

1 个答案:

答案 0 :(得分:0)

递归解决方案,不是你要求的,但我希望它有所帮助。

我们将使用一个函数来检查矩阵的每个元素的出现次数。如果grid[1][1]匹配字符串的第一个字符,我们需要检查对角线相邻元素是否与字符串的第二个字符匹配。我们可以删除字符串的第一个字符,只需使用新字符串在相邻元素上调用相同的函数。

(Python代码,但即使你不了解Python也应该是可以理解的)

首先,我们创建一个辅助函数来返回有效的对角线邻居。

def valid_neighbors(i,j, N):
    # Returns a list of valid diagonal neighbors(Do not exceed matrix borders).
    neighbors = [(i-1, j-1), (i+1, j+1), (i+1, j-1), (i-1, j+1)]
    return [m for m in neighbors if  (0 <= m[0] < N) and (0 <= m[1] < N)]

接下来是检查事件的递归函数(注释解释逻辑)。

def find(matrix, N, i, j, string):
    occurrences = 0
    if string == matrix[i][j]:
        # Found one occurrence, nothing else to do.
        return 1
    if string[0] == matrix[i][j]:
        # First letter of the string match, seek for possible occurrences.
        for new_i, new_j in valid_neighbors(i, j, N):
            # Go over all valid diagonal moves
            if matrix[new_i][new_j] == string[1]:
                # If the char in the new location match the next character of the string,
                # recursively call this function with the new position and the input string
                # minus the first character ("ABCD" -> "BCD").
                occurrences += find(matrix, N, new_i, new_j, string[1:])
    # Finally return the number of occurrences found.
    return occurrences

它适用于矩阵的单个元素,我们需要为每个元素调用函数并对结果求和。

def wrapper(matrix, string):
    # Call find on every element of the matrix and sum the results.
    occurrences = 0
    N = len(matrix)
    for i in range(N):
        for j in range(N):
            occurrences += find(matrix, N, i, j, string)
    return occurrences

您可以构建一个缓存机制来提高性能。

在输入矩阵上运行代码:

mat = [
       ['B', 'X', 'A', 'X', 'X'],
       ['X', 'A', 'X', 'X', 'X'],
       ['X', 'B', 'B', 'X', 'X'],
       ['X', 'A', 'X', 'A', 'X'],
       ['X', 'X', 'B', 'X', 'X']
       ]
print wrapper(mat, "ABA")
14