题解 | #牛群的活动区域#

牛群的活动区域

https://www.nowcoder.com/practice/eabeca0c6e944a618f8adfed128d847e

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param board char字符型二维数组
 * @param boardRowLen int board数组行数
 * @param boardColLen int* board数组列数
 * @return char字符型二维数组
 * @return int* returnSize 返回数组行数
 * @return int** returnColumnSizes 返回数组列数
 */
void dfs(char** board, int m, int n, int i, int j, int** visited,
         int** canwrite) {
    if (i < 0 || j < 0 || i >= m || j >= n || visited[i][j] != 0 ||
            board[i][j] == 'A') return;
    visited[i][j] = 1;
    canwrite[i][j] = -1;
    dfs(board, m, n, i - 1, j, visited, canwrite);
    dfs(board, m, n, i + 1, j, visited, canwrite);
    dfs(board, m, n, i, j - 1, visited, canwrite);
    dfs(board, m, n, i, j + 1, visited, canwrite);
    visited[i][j] = 0;
}
char** solve(char** board, int boardRowLen, int* boardColLen, int* returnSize,
             int** returnColumnSizes ) {
    // write code here
    int m = boardRowLen, n = boardColLen[0];
    *returnSize = m;
    *returnColumnSizes = malloc(sizeof(int) * m);
    for (int i = 0; i < m; i++) {
        (*returnColumnSizes)[i] = n;
    }
    int** visited = malloc(sizeof(int*)*m);
    int** canwrite = malloc(sizeof(int*)*m);
    for (int i = 0; i < m; i++) {
        visited[i] = malloc(sizeof(int) * n);
        canwrite[i] = malloc(sizeof(int) * n);
        for (int j = 0; j < n; j++) {
            visited[i][j] = 0;
            canwrite[i][j] = 0;
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                if (board[i][j] == 'B') {
                    canwrite[i][j] = -1;
                    dfs(board, m, n, i, j, visited, canwrite);
                }
            }
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (canwrite[i][j] != -1) board[i][j] = 'A';
        }
    }
    return board;
}

全部评论

相关推荐

10-29 15:38
门头沟学院 Java
榕城小榕树:难道你简历里写了配送路径优化算法?
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务