LeetCode - 695. Max Area of Island (Java)
R、C记录矩阵行列
可以将邻接矩阵转为邻接表来做,即要将二维数组转换为一维数组:
将二维坐标转化为一维坐标:
V = x * C + y
若将一维坐标转化为二维坐标:
x = V / C
y = V % C
dfs返回以v顶点出发所在联通分量的顶点数
1 import java.util.HashSet; 2 3 class Solution { 4 private int R, C; 5 private HashSet<Integer>[] G; 6 private boolean[] visited; 7 private int dirs[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 8 9 public int maxAreaOfIsland(int[][] grid) { 10 11 if (grid == null) return 0; 12 R = grid.length; 13 if (R == 0) return 0; 14 C = grid[0].length; 15 if (C == 0) return 0; 16 17 G = constructGraph(grid); 18 visited = new boolean[G.length]; 19 20 int res = 0; 21 for (int v = 0; v < G.length; v++) { 22 int x = v / C, y = v % C; 23 if (!visited[v] && grid[x][y] == 1) 24 res = Math.max(res, dfs(v)); 25 } 26 return res; 27 } 28 29 private int dfs(int v) { 30 visited[v] = true; 31 int ret = 1; 32 for (int w : G[v]) 33 if (!visited[w]) 34 ret += dfs(w); 35 return ret; 36 } 37 38 public HashSet<Integer>[] constructGraph(int[][] grid) { 39 HashSet<Integer>[] g = new HashSet[R * C]; 40 for (int i = 0; i < g.length; i++) 41 g[i] = new HashSet<>(); 42 for (int v = 0; v < g.length; v++) { 43 int x = v / C, y = v % C; 44 if (grid[x][y] == 1) { 45 for (int d = 0; d < 4; d++) { 46 int nextX = x + dirs[d][0]; 47 int nextY = y + dirs[d][1]; 48 if (inArea(nextX, nextY) && grid[nextX][nextY] == 1) { 49 int next = nextX * C + nextY; 50 g[v].add(next); 51 g[next].add(v); 52 } 53 } 54 } 55 } 56 return g; 57 } 58 59 private boolean inArea(int x, int y) { 60 return x >= 0 && x < R && y >= 0 && y < C; 61 } 62 }
但实际上没必要建邻接表来做,可以直接操作二维数组,即使用floodfill的算法来完成,代码如下:
1 import java.util.HashSet; 2 3 class Solution { 4 private int R, C; 5 private int[][] grid; 6 private boolean[][] visited; 7 private int dirs[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 8 9 public int maxAreaOfIsland(int[][] grid) { 10 11 if (grid == null) return 0; 12 R = grid.length; 13 if (R == 0) return 0; 14 C = grid[0].length; 15 if (C == 0) return 0; 16 17 this.grid = grid; 18 visited = new boolean[R][C]; 19 int res = 0; 20 for (int x = 0; x < R; x++) { 21 for (int y = 0; y < C; y++) { 22 if (!visited[x][y] && grid[x][y] == 1) 23 res = Math.max(res, dfs(x, y)); 24 } 25 } 26 return res; 27 } 28 29 private int dfs(int x, int y) { 30 visited[x][y] = true; 31 int ret = 1; 32 33 for (int d = 0; d < 4; d++) { 34 int nextX = x + dirs[d][0]; 35 int nextY = y + dirs[d][1]; 36 if (inArea(nextX, nextY) && !visited[nextX][nextY] && grid[nextX][nextY] == 1) 37 ret += dfs(nextX, nextY); 38 } 39 return ret; 40 } 41 42 private boolean inArea(int x, int y) { 43 return x >= 0 && x < R && y >= 0 && y < C; 44 } 45 }