用于在编译器上运行的代码
便于修改、理解深度优先搜索:
package com.company;
/**
* 给定一个包含了一些 0 和 1 的非空二维数组grid 。
*
* 一个岛屿是由一些相邻的1(代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设grid 的四个边缘都被 0(代表水)包围着。
*
* 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。)
*
*
* 示例 1:
*
* [[0,0,1,0,0,0,0,1,0,0,0,0,0],
* [0,0,0,0,0,0,0,1,1,1,0,0,0],
* [0,1,1,0,1,0,0,0,0,0,0,0,0],
* [0,1,0,0,1,1,0,0,1,0,1,0,0],
* [0,1,0,0,1,1,0,0,1,1,1,0,0],
* [0,0,0,0,0,0,0,0,0,0,1,0,0],
* [0,0,0,0,0,0,0,1,1,1,0,0,0],
* [0,0,0,0,0,0,0,1,1,0,0,0,0]]
* 对于上面这个给定矩阵应返回6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。
*
* 示例 2:
*
* [[0,0,0,0,0,0,0,0]]
* 对于上面这个给定的矩阵, 返回0。
*
* 注意: 给定的矩阵grid 的长度和宽度都不超过 50。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/max-area-of-island
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
import java.util.Arrays;
import java.util.Random;
/**
* 生成0-1的随机整数
*/
class RandomNum{
public void randomNum(int[][] grid){
Random random = new Random();
int max = 2;
int min = 0;
for(int i = 0; i< grid.length; i++){
for (int j = 0; j< grid[0].length; j++){
grid[i][j] = (random.nextInt(max) % (max - min + 1));
}
}
}
}
/**
* 深度优先搜索
*/
class Solution {
/**
* dx dy是用于向四个方向移动的数组
*/
int[] dx = {1,0,0,-1};
int[] dy = {0,1,-1,0};
public int maxAreaOfIsland(int[][] grid) {
int ans = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j< grid[0].length; j++){
ans = Math.max(ans, dfs(grid, i, j));
}
}
return ans;
}
public int dfs(int[][] grid, int x, int y){
int r = grid.length, c = grid[0].length;
if( x < 0 || y < 0 || x == r || y == c || grid[x][y] != 1){
return 0;
}
int ans = 1;
// 遍历过的位置都赋值为0,防止多次遍历同一位置
grid[x][y] = 0;
for(int i = 0; i < 4; i++){
int mx = x + dx[i], my = y + dy[i];
// 此处if判断多余了
if( mx >= 0 && mx < r && my >= 0 && my < c){
grid[x][y] = 0;
ans += dfs(grid, mx, my);
}
}
return ans;
}
}
/**
* @author codexy
*/
public class MaxAreaOfIsland{
public static void main(String[] args) {
// 初始化二维数组
int[][] grid = new int [50][50];
// 实例化RandomNum类对象
RandomNum num = new RandomNum();
// 调用RandomNum内的randomNum方法 对grid内的所有索引位置 赋值0-1的随机整数
num.randomNum(grid);
// 实例化Solution类对象
Solution areas = new Solution();
// 查看grid数组
for (int i = 0; i < grid.length ; i++) {
System.out.println(Arrays.toString(grid[i]));
}
// 调用Solution内的maxAreaOfIsland方法并输出其返回值
System.out.println(areas.maxAreaOfIsland(grid));
}
}