1
+ class Solution {
2
+ // S - start, U - Up, D - Down, O- out of bound/0, R- Right, L-Left
3
+ public int numDistinctIslands (int [][] grid ) {
4
+ if (grid == null || grid .length == 0 ) {
5
+ return 0 ;
6
+ }
7
+ HashSet <String > set = new HashSet <>();
8
+ for (int i =0 ; i <grid .length ; i ++) {
9
+ for (int j =0 ; j <grid [0 ].length ; j ++) {
10
+ if (grid [i ][j ] == 1 ) {
11
+ String island = dfs (grid , i , j , grid .length , grid [0 ].length , "S" );
12
+ set .add (island );
13
+ }
14
+ }
15
+ }
16
+ return set .size ();
17
+ }
18
+
19
+ public String dfs (int [][] grid , int row , int col , int m , int n , String dir ) {
20
+ if (row < 0 || row >= grid .length || col < 0 || col >= grid [0 ].length || grid [row ][col ] == 0 ) {
21
+ return "O" ;
22
+ }
23
+ grid [row ][col ] = 0 ;
24
+ String left = dfs (grid , row , col -1 , m , n , "L" );
25
+ String up = dfs (grid , row -1 , col , m , n , "U" );
26
+ String down = dfs (grid , row +1 , col , m , n , "D" );
27
+ String right = dfs (grid , row , col +1 , m , n , "R" );
28
+
29
+ return dir + left + up + down + right ;
30
+ }
31
+ }
0 commit comments