|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74 |
#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("\n"); 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:
首先在二维数组中找到字符串的首个字符,然后一直按照某个方向进行搜索,直到把整个字符串搜出来为止;
详细代码如下:
原文:http://www.cnblogs.com/scottding/p/3651620.html