200. Number of Islands

╰半橙微兮° 2022-02-12 11:47 340阅读 0赞
  1. 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.
  2. Example 1:
  3. Input:
  4. 11110
  5. 11010
  6. 11000
  7. 00000
  8. Output: 1
  9. Example 2:
  10. Input:
  11. 11000
  12. 11000
  13. 00100
  14. 00011
  15. Output: 3

本题是一个非常经典的深度优先搜索的题目(代码我都能背出来了)。代码如下:

  1. int[] dx = new int[]{0, 1, 0, -1};
  2. int[] dy = new int[]{1, 0, -1, 0};
  3. public int numIslands(char[][] grid) {
  4. int ans = 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') {
  8. ++ans;
  9. grid[i][j] = '0';
  10. dfs(i, j, grid);
  11. }
  12. }
  13. }
  14. return ans;
  15. }
  16. private void dfs(int i, int j, char[][] grid) {
  17. for(int k = 0; k < 4; ++k) {
  18. int x = i + dx[k];
  19. int y = j + dy[k];
  20. if(0 <= x && x < grid.length && 0 <= y && y < grid[0].length && grid[x][y] == '1') {
  21. grid[x][y] = '0';
  22. dfs(x, y, grid);
  23. }
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,340人围观)

还没有评论,来说两句吧...

相关阅读