FB面经 Prepare: Count Unique Island
数unique island, 比如 110000 110001 001101 101100 100000 总共两个unique岛,不是四个
方法可以是记录每次新的岛屿搜索的路径,left,right,up,down, 作为标志是否相同的key,存hashset
1 package fbOnsite; 2 import java.util.*; 3 public class UniqueIsland { 4 public int countIsland(int[][] grid) { 5 HashSet<String> set = new HashSet<String>(); 6 7 for (int i=0; i<grid.length; i++) { 8 for (int j=0; j<grid[0].length; j++) { 9 if (grid[i][j] != 1) continue; 10 StringBuilder path = new StringBuilder(); 11 dfs(grid, i, j, path.append('s')); //start 12 set.add(path.toString()); 13 } 14 } 15 16 for(String str : set) { 17 System.out.println(str); 18 } 19 20 return set.size(); 21 } 22 23 public void dfs(int[][] grid, int i, int j, StringBuilder sb) { 24 grid[i][j] = 2; 25 //up 26 if (i>=1 && grid[i-1][j]==1) dfs(grid, i-1, j, sb.append('u')); 27 //right 28 if (j<grid[0].length-1 && grid[i][j+1]==1) dfs(grid, i, j+1, sb.append('r')); 29 //down 30 if (i<grid.length-1 && grid[i+1][j]==1) dfs(grid, i+1, j, sb.append('d')); 31 //left 32 if (j>=1 && grid[i][j-1]==1) dfs(grid, i, j-1, sb.append('l')); 33 } 34 35 /** 36 * @param args 37 */ 38 public static void main(String[] args) { 39 // TODO Auto-generated method stub 40 UniqueIsland sol = new UniqueIsland(); 41 int[][] grid = new int[][]{{1,1,0,0,0,0},{1,1,0,0,0,1},{0,0,1,1,0,0},{1,0,1,1,0,0,},{1,0,0,0,0,0}}; 42 int res = sol.countIsland(grid); 43 System.out.println(res); 44 } 45 46 }