經典考題二 數島嶼
阿新 • • 發佈:2021-12-08
860 · Number of Distinct Islands
Algorithms
Medium
Description
Given a non-empty 2D arraygrid
of 0's and 1's, anislandis a group of1
's (representing land) connected 4-directionally (horizontal or vertical). You may assume all four edges of the grid are surrounded by water.
Count the number ofdistinctislands. An island is considered to be the same as another if and only if one island has the same shape as another island (and not rotated or reflected).
Notice that:
11
1
and
1
11
are considered different island, because we do not consider reflection / rotation.
The length of each dimension in the givengrid
does not exceed50
.
Example 1:
Input: [ [1,1,0,0,1], [1,0,0,0,0], [1,1,0,0,1], [0,1,0,1,1] ] Output: 3 Explanation: 11 1 1 1 11 11 1
Example 2:
Input:
[
[1,1,0,0,0],
[1,1,0,0,0],
[0,0,0,1,1],
[0,0,0,1,1]
]
Output: 1
解法,只需要在dfs基礎上增加path去跟蹤遍歷路徑,如果遍歷路徑相同的即為同樣形狀的島嶼
public class Solution { public int numberofDistinctIslands(int[][] grid) { if(grid==null || grid.length==0) return 0; Set<String> set = newHashSet(); for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ if(grid[i][j]==1) { path=""; dfs(grid,i,j,"start"); set.add(path); } } } return set.size(); } private String path = ""; private void dfs(int[][] grid,int x,int y,String direct){ path+=direct+"#"; if(x<0 || x>=grid.length || y<0 || y>=grid[0].length || grid[x][y]==0 ) { return; } grid[x][y] = 0; dfs(grid,x-1,y,"l"); dfs(grid,x+1,y,"r"); dfs(grid,x,y-1,"u"); dfs(grid,x,y+1,"d"); } }