其实这题代码很简单,可能就思路比较难想(虽然题目标签是bfs,但我想不出来bfs思路是什么,所有这里我们使用dfs)
思路:在整个方阵外层套一圈0,然后把闭合圈外的0都变成-1即可,剩下的0就是闭合圈内的0。最后输出时把-1输出为0,1输出为1,0输出为2.
OVER
代码里注释很详细:
package search;
import java.util.Scanner;
public class P1162 {
static int n, arr[][];
static int[] x = { 1, -1, 0, 0 };// 四个方向
static int[] y = { 0, 0, -1, 1 };
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
arr = new int[n + 2][n + 2];
//在整个方阵外套一层,防止原方阵第一个坐标就是1
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
arr[i][j] = sc.nextInt();
}
}
//这是没处理之前的方阵,可以放开注释看看
// for (int i = 0; i <= n+1; i++) {
// for (int j = 0; j <= n+1; j++) {
// System.out.printf("%3d",arr[i][j]);
// }
// System.out.println();
// }
dfs(0, 0);
//不懂dfs干嘛的可以把下面这段注释放开,输出的是改变后的arr方阵,一看就懂
// for (int i = 0; i < n+1; i++) {
// for (int j = 0; j < n+1; j++) {
// System.out.printf("%3d",arr[i][j]);
// }
// System.out.println();
// }
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (arr[i][j] == -1) {
System.out.print(0 + " ");
}
if (arr[i][j] == 1) {
System.out.print(1 + " ");
}
if (arr[i][j] == 0) {
System.out.print(2 + " ");
}
}
System.out.println();
}
}
/**
* 作用:把闭合圈外围的0变成-1,其余不变,这样一来剩下的0就是闭合圈里面的0,最后进行相应输出即可
* @param row 起始横坐标
* @param col 起始纵坐标
*/
public static void dfs(int row, int col) {
if (arr[row][col] != 0) {//
return;
}
arr[row][col] = -1;// -1代表闭合圈外围的0
for (int i = 0; i < 4; i++) {
//注意不要像这样提前赋值,会影响下一次循环的row和col
//尽量在函数里传参数
// row = row + x[i];
// col = col + y[i];
if (row+ x[i] >= 0 && row+ x[i] <= n+1 && col+ y[i] >= 0 && col+ y[i] <= n+1) {
dfs(row + x[i], col + y[i]);
}
}
}
}