Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)輸入一個非空的二維數組,數組由0和1組成。其中0表明水域,1表示陸地。咱們須要找出整個數組所表示的地圖中,面積最大的一塊陸地(陸地的相連只看上下左右相鄰的4個元素,如左上方這種就不算相鄰!)。數組
Example 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, 由於陸地相連要求必須是在上下左右四個方向。
Example 2:
[[0,0,0,0,0,0,0,0]]
返回應爲0.code
int[][] directions = {{-1,0},{1,0},{0,-1},{0,1}}; public int maxAreaOfIsland(int[][] grid) { int rows = grid.length; int cols = grid[0].length; int maxArea = 0; int currArea = 0; for(int row=0;row<rows;row++){ for(int col=0;col<cols;col++){ if(grid[row][col] == 1){ grid[row][col] = 0; currArea = findArea(grid,row,col); maxArea = Math.max(currArea, maxArea); } } } return Math.max(maxArea, currArea); } public int findArea(int[][] grid,int x,int y){ int area = 1; for(int[] direction : directions){ int newX = x+direction[0]; int newY = y+direction[1]; if( newX>=0 && newX < grid.length && newY >=0 && newY < grid[0].length){ if(grid[newX][newY] == 1){ grid[newX][newY] = 0; area += findArea(grid,newX,newY); } } } return area; }