开心消消乐
给定一个N行M列的二维矩阵,矩阵中每个位置的数字取值为0或1。矩阵示例如:
1 1 0 0
0 0 0 1
0 0 1 1
1 1 1 1
现需要将矩阵中所有的1进行反转为0,规则如下:
1)当点击一个1时,该1变被反转为0,同时相邻的上、下、左、右,以及左上、左下、右上、右下8个方向的1(如果存在1)均会自动反转为0;
2〉进一步地,一个位置上的1被反转为0时,与其相邻的8个方向的1(如果存在1)均会自动反转为0;按照上述规则示例中的矩阵只最少需要点击2次后,所有值均为0。请问,给定一个矩阵,最少需要点击几次后,所有数字均为0?
输入描述:
第一行为两个整数,分别表示矩阵的行数N和列数M,取值范围均为[1,100]
接下来N行表示矩阵的初始值,每行均为M个数,取值范围[0,1]
输出描述:
输出一个整数,表示最少需要点击的次数
示例1
输入:
3 3
1 0 1
0 1 0
1 0 1
输出:
1
说明:
上述样例中,四个角上的1均在中间的1的相邻8个方向上,因此只需要点击一次即可
示例2
输入∶
4 4
1 1 0 0
0 0 0 1
0 0 1 1
1 1 1 1
输出:
2
说明:
在上述4*4的矩阵中,只需要点击2次,即可将所有的1进行消除
个人解法
不保证通过率
public class Main {
public static boolean[][] status;
public static int result = 0;
public static void main(String[] args) {
// status = new boolean[3][3];
// int[][] nums = new int[][]{{1, 0, 1}, {0, 0, 0}, {1, 0, 1}};
status = new boolean[4][4];
int[][] nums = new int[][]{{1, 1, 0, 1}, {0, 0, 0, 1}, {0, 0, 1, 1}, {1, 1, 1, 1}};
int lenx = nums.length, leny = nums[0].length;
for (int i = 0; i < lenx; i++) {
for (int j = 0; j < leny; j++) {
if (!status[i][j] && nums[i][j] == 1) {
use(nums, i, j);
result++;
}
}
}
System.out.println(result);
}
public static void dfs(int[][] nums, int x, int y) {
int lenx = nums.length, leny = nums[0].length;
if (x < 0 || x > lenx - 1 || y < 0 || y > leny - 1 || nums[x][y] == 0) return;
use(nums, x, y);
}
private static void use(int[][] nums, int x, int y) {
status[x][y] = true;
nums[x][y] = 0;
dfs(nums, x - 1, y);
dfs(nums, x - 1, y + 1);
dfs(nums, x - 1, y - 1);
dfs(nums, x, y + 1);
dfs(nums, x, y - 1);
dfs(nums, x + 1, y);
dfs(nums, x + 1, y - 1);
dfs(nums, x + 1, y + 1);
}
}