leetcode 695 Max Area of Island

題目詳情

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

想法

  • 咱們仍是要遍歷數組中的每個元素。
  • 若是數組元素值爲1,則咱們以這個值爲起點進行深度優先搜索。
  • 遍歷當前元素的相鄰元素,若是有相鄰元素的值爲1,那麼再以這個元素爲起點繼續搜索。
  • 爲了防止重複,咱們每發現一個值爲1的元素,就將這個元素賦值爲0,表明咱們已經遍歷過這個元素了。

解法

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;
    }
相關文章
相關標籤/搜索