leetcode 694 不同的岛屿数量
作者:互联网
不同的岛屿数量
其中有四个岛屿,但是左下角和右上角的岛屿形状相同,所以不同的岛屿共有三个,算法返回 3。
考点:
1. DFS
2. 序列化
3. 去重操作
public class Solution { /** * @param grid: a list of lists of integers * @return: return an integer, denote the number of distinct islands */ public int numberofDistinctIslands(int[][] grid) { // write your code here int m = grid.length; int n = grid[0].length; HashSet<String> islands = new HashSet<>(); for(int i = 0; i< m; i++){ for(int j = 0; j<n;j++){ if(grid[i][j] == 1){ StringBuilder sb = new StringBuilder(); dfs(grid, i, j, sb, 0); islands.add(sb.toString()); } } } return islands.size(); } private void dfs(int[][] grid , int i , int j , StringBuilder sb, int dir){ int m = grid.length; int n = grid[0].length; if (i < 0 || j < 0 || i >= m||j>= n || grid[i][j] == 0){ return; } grid[i][j] = 0; sb.append(dir).append(','); dfs(grid,i-1,j,sb,1);//上 dfs(grid,i+1,j,sb,2);//下 dfs(grid,i,j-1,sb,3);//左 dfs(grid, i, j+1, sb, 4);//右 sb.append(-dir).append(','); } }
标签:return,694,int,岛屿,dfs,grid,sb,leetcode,append 来源: https://www.cnblogs.com/lzw-lxy/p/16098424.html