题解 | #牛群的活动区域#
牛群的活动区域
https://www.nowcoder.com/practice/eabeca0c6e944a618f8adfed128d847e
题目考察的知识点是:
深度优先搜索算法。
题目解答方法的文字分析:
本题先获取二维数组的长度,然后使用循环后多个递归去设置相应的值,最后得到结果。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param board char字符型二维数组 * @return char字符型二维数组 */ public char[][] solve (char[][] board) { // write code here int n = board.length; int m = board[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (board[i][j] == 'B') { test(board, i, j); } } } return board; } public void test(char[][] board, int i, int j) { int n = board.length; int m = board[0].length; if (i >= n - 1 || i <= 0 || j >= m - 1 || j <= 0 || board[i][j] == 'A'){ return; } board[i][j] = 'A'; test(board, i - 1, j); test(board, i, j - 1); test(board, i + 1, j); test(board, i, j + 1); } }#题解#