国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode: Number of Islands

2019-11-14 23:43:16
字體:
來源:轉載
供稿:網友
Leetcode: Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.Example 1:11110110101100000000Answer: 1Example 2:11000110000010000011Answer: 3

DFS的Flood Fill方法,

使用額外Visited數組的做法:

 1 public class Solution { 2     public int numIslands(char[][] grid) { 3         if (grid==null || grid.length==0 || grid[0].length==0) return 0; 4         int count = 0; 5         boolean[][] visited = new boolean[grid.length][grid[0].length]; 6         for (int i=0; i<grid.length; i++) { 7             for (int j=0; j<grid[0].length; j++) { 8                 if (grid[i][j] != '1') continue; 9                 else {10                     count++;11                     floodFill(grid, i, j, visited);12                 }13             }14         }15         return count;16     }17     18     public void floodFill(char[][] grid, int i, int j, boolean[][] visited) {19         if (i<0 || i>=grid.length || j<0 || j>=grid[0].length) return;20         if (visited[i][j]) return;21         if (grid[i][j] != '1') return;22         grid[i][j] = '2';23         floodFill(grid, i-1, j, visited);24         floodFill(grid, i+1, j, visited);25         floodFill(grid, i, j-1, visited);26         floodFill(grid, i, j+1, visited);27     }28 }

更節省空間的方法:不使用額外visited數組,但是用‘1’變成‘2’表示visited的方法

 1 public class Solution { 2     public int numIslands(char[][] grid) { 3         if (grid==null || grid.length==0 || grid[0].length==0) return 0; 4         int count = 0; 5         for (int i=0; i<grid.length; i++) { 6             for (int j=0; j<grid[0].length; j++) { 7                 if (grid[i][j] != '1') continue; 8                 else { 9                     count++;10                     floodFill(grid, i, j);11                 }12             }13         }14         return count;15     }16     17     public void floodFill(char[][] grid, int i, int j) {18         if (i<0 || i>=grid.length || j<0 || j>=grid[0].length) return;19         if (grid[i][j] != '1') return; //either 0(water) or 2(visited)20         grid[i][j] = '2';21         floodFill(grid, i-1, j);22         floodFill(grid, i+1, j);23         floodFill(grid, i, j-1);24         floodFill(grid, i, j+1);25     }26 }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 延长县| 邵东县| 安达市| 霸州市| 平乐县| 建水县| 清河县| 土默特右旗| 望城县| 延长县| 巴马| 布拖县| 蒲江县| 伊春市| 梅河口市| 临猗县| 毕节市| 瑞安市| 临潭县| 荥经县| 博野县| 江都市| 东台市| 滨州市| 丽江市| 信宜市| 白河县| 安乡县| 镇康县| 和田县| 鄂伦春自治旗| 湖口县| 祁门县| 荔浦县| 盐池县| 即墨市| 双柏县| 富源县| 炉霍县| 青州市| 房产|