LeetCode - 695. Max Area of Island (Java)
生活随笔
收集整理的這篇文章主要介紹了
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 }?
轉載于:https://www.cnblogs.com/AntonLiu/p/11289238.html
總結
以上是生活随笔為你收集整理的LeetCode - 695. Max Area of Island (Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个vue管理系统的初步搭建总结
- 下一篇: bobo老师机器学习笔记1.1 - 什么