具体题目描述见:http://www.careercup.com/question?id=13126665
对于这个题目我想到的方法是暴力搜索,因为目标串已经给定,如果我们将矩阵中每个属于目标串的字符看做图的结点,如果目标串中出现形如“AB”的子串且A和B在字符矩阵中相邻,则在建立一条由A到B的有向边。我们只需要搜索一条长度和目标串长度相同的路径即可。代码如下:
1 #include <stdio.h> 2 #define M 100 3 #define N 50 4 5 char str[M + 1][M + 1]; 6 char pat[N + 1]; 7 int lp; 8 char flag[M + 1][M + 1]; 9 int n, m; 10 11 int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1}; 12 int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1}; 13 14 int do_dfs(int x, int y, int idx) { 15 int i, tx, ty; 16 if (idx == lp - 1) { 17 return 1; 18 } 19 else { 20 for (i = 0; i < 8; i++) { 21 tx = (x + dx[i] + n) % n; 22 ty = (y + dy[i] + m) % m; 23 if ((!flag[tx][ty]) && (str[tx][ty] == pat[idx + 1])) { 24 flag[tx][ty] = 1; 25 if (do_dfs(tx, ty, idx + 1)) { 26 return 1; 27 } 28 else { 29 flag[tx][ty] = 0; 30 } 31 } 32 } 33 } 34 return 0; 35 } 36 37 int is_matching() 38 { 39 int x, y, i, j; 40 for (x = 0; x < n; x++) { 41 for (y = 0; y < m; y++) { 42 for (i = 0; i < n; i++) { 43 for (j = 0; j < m; j++) { 44 flag[i][j] = 0; 45 } 46 } 47 48 if (str[x][y] == pat[0]) { 49 flag[x][y] = 1; 50 if (do_dfs(x, y, 0)) { 51 return 1; 52 } 53 } 54 } 55 } 56 return 0; 57 } 58 59 int main() 60 { 61 int i; 62 n = 5, m = 5; 63 str[0][0] = 'a', str[0][1] = 'c', str[0][2] = 'p', str[0][3] = 'r', str[0][4] = 'c'; 64 str[1][0] = 'x', str[1][1] = 's', str[1][2] = 'o', str[1][3] = 'p', str[1][4] = 'c'; 65 str[2][0] = 'v', str[2][1] = 'o', str[2][2] = 'v', str[2][3] = 'n', str[2][4] = 'i'; 66 str[3][0] = 'w', str[3][1] = 'g', str[3][2] = 'f', str[3][3] = 'm', str[3][4] = 'n'; 67 str[4][0] = 'q', str[4][1] = 'a', str[4][2] = 't', str[4][3] = 'i', str[4][4] = 't'; 68 gets(pat); 69 lp = strlen(pat); 70 printf("%d\n", is_matching()); 71 return 0;
浙公网安备 33010602011771号