题解 | #童谣寻找问题#
童谣寻找问题
https://www.nowcoder.com/practice/2537c84de0034d019b1679cf7bfcf776
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param board char字符型二维数组 * @param boardRowLen int board数组行数 * @param boardColLen int* board数组列数 * @param word string字符串 * @return bool布尔型 */ void dfs(char** board, int m, int n, int i, int j, int current, char* word, int* flag, int** visited) { if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[current] || visited[i][j] == 1) return; if (current + 1 == strlen(word) && board[i][j] == word[current]) { (*flag) = 1; return; } visited[i][j] = 1; dfs(board, m, n, i + 1, j, current + 1, word, flag, visited); dfs(board, m, n, i - 1, j, current + 1, word, flag, visited); dfs(board, m, n, i, j - 1, current + 1, word, flag, visited); dfs(board, m, n, i, j + 1, current + 1, word, flag, visited); visited[i][j] = 0; } bool exist(char** board, int boardRowLen, int* boardColLen, char* word ) { // write code here int len = strlen(word); int current = 0; int m = boardRowLen, n = boardColLen[0]; int** visited = malloc(sizeof(int*)*m); for (int i = 0; i < m; i++) { visited[i] = malloc(sizeof(int) * n); for (int j = 0; j < n; j++) { visited[i][j] = 0; } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == word[0]) { int flag = 0; dfs(board, m, n, i, j, current, word, &flag, visited); if (flag) return true; } } } return false; }