public int numDistinctIslands(int[][] grid) {
if (grid == null || grid.length == 0) {
int m = grid.length, n = grid[0].length;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
String[] symbols = {"d", "u", "l", "r"};
Set<String> set = new HashSet<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
StringBuilder key = new StringBuilder();
searchDistinctIslandByDFS(i, j, "s", key, directions, symbols, grid);
public void searchDistinctIslandByDFS(int row, int col, String symbol, StringBuilder key, int[][] directions, String[] symbols, int[][] grid) {
for (int i = 0; i < directions.length; i++) {
int nextRow = row + directions[i][0];
int nextCol = col + directions[i][1];
if (isValid(nextRow, nextCol, grid)) {
searchDistinctIslandByDFS(nextRow, nextCol, symbols[i], key, directions, symbols, grid);
public boolean isValid(int row, int col, int[][] grid) {
return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1;