字符串搜索

#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
using namespace std ;

char grid[100][100] , word[100] ;
int n , m ;

int x[] = {-1 , -1 , -1 , 0 , 0 , 1 , 1 , 1} ;
int y[] = {-1 , 0 , 1 , -1 , 1 , -1 , 0 , 1} ;

int xx , yy ;

void Search()	{
	int len = strlen(word) , k ;
	for( int i = 0 ; i < n ; i++ )	
		for(int j = 0 ; j < m ; j++ )	{	
			if(grid[i][j] == word[0])	{
				for(int ii = 0 ; ii < 8 ; ii++)	{
					xx = i , yy = j ;
					for( k = 1 ; k < len ; k++)	{
						xx = xx+x[ii] ;
						yy = yy+y[ii] ;
						if(xx < 0 || xx >= n || yy < 0 || yy >= m )
							break ;
						if(grid[xx][yy] != word[k])
							break ;
					}
					if(k == len)	{
						xx = i , yy = j ;
						return ;
					}
				}
			}
		}
}


int main()	{
	int N ;
	cin >> N ;
	int t = 0 ;
	while(N--)	{
		if(t)
		 printf("
");
		t = 1 ;
		cin >> n >> m ;
		int i , j , k ;
		for(i = 0 ; i < n ; i++)	{
			for(j = 0 ; j < m ; j++)	{
				char c ;
				cin >> c ;
				if(c >= 'A' && c <= 'Z')
					c += 32 ;
				grid[i][j] = c ;
			}
		}
		int t ;
		cin >> t ;
		for(i = 0 ; i < t ; i++)	{
			cin >> word ;
			for(j = 0 ; j < strlen(word) ; j++)	{
				if(word[j] >= 'A' && word[j] <= 'Z')	
					word[j] += 32 ;
			}
			Search() ;
			cout << xx + 1 << " " << yy + 1 << endl ;
		}
	}
	return 0 ;
}

			

在二维数组中存入字符,然后再输入一个字符串,在二维数组中查找字符串;

中间犯了一个错误,以为简单的BFS,其实不是这样的。

Process:

  首先在二维数组中找到字符串的首个字符,然后一直按照某个方向进行搜索,直到把整个字符串搜出来为止;

详细代码如下:

原文地址:https://www.cnblogs.com/scottding/p/3651620.html