695. The maximum area of the island (deep search)

A recursive algorithm was so beautiful

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     static int Area,Col,Row,temp;
11     static int[][] grid;
12     static int[][] dxy={{0,1},{1,0},{0,-1},{-1,0}}; //四联通分量
13 
14     private void dfs(int i,intJ) {
 15          TEMP ++ ;
 16          Grid [I] [J] = 0; // remove Calculated island block 
. 17          for ( int K = 0; K <. 4; K ++ ) {
 18 is              int X = I + DXY [K] [0], Y = J + DXY [K] [. 1 ];
 . 19              IF (X> = 0 && X <CoI && Y> = 0 && Y <Row && Grid [X] [Y] ==. 1 ) DFS (X, Y);
 20 is          }
 21 is      }
 22 is  
23 is      public  int maxAreaOfIsland ( int [] [] Grid) {
 24          // initial global variables 
25          Area = 0 ;
 26 is          CoI = grid.length;
 27         = Grid Row [0 ] .length;
 28          the this .grid = Grid;
 29          // loop inlet 
30          for ( int I = 0; I <grid.length; I ++ ) {
 31 is              for ( int J = 0; J <Grid [ 0] .length; J ++ ) {
 32                  IF (Grid [I] [J] ==. 1) { //
 33 is                      TEMP 0 =;   // set the value of the initial area 
34 is                      DFS (I, J); // recursive search 
35                      IF (area <TEMP) area = TEMP; // the island to island block has a recording area value is compared 
36                  }
 37              }
38         }
39         return Area;
40     }
41 }

 

Guess you like

Origin www.cnblogs.com/NiBosS/p/12003806.html