LeetCode Number of Islands Java版本

来源:互联网 发布:linux 内存信息 编辑:程序博客网 时间:2024/06/05 04:51

题目描述:

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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3




题目分析:

这道题解题思路很简单,就是从找到的一个‘1’开始,递归遍历(深度优先搜索)它的上下左右位置。

这道题开始困惑我的地方是Java的参数传递方式,纠结了半天,后来才恍然大悟。。。。果然还是掌握的不够熟练。。。


代码如下:


public class Solution {    char[][] map;    int[][] visit;    int m,n;        public void findIsland(int i,int j){        visit[i][j] = 1;        if(i-1>=0 && map[i-1][j]=='1' && visit[i-1][j]==0){            visit[i-1][j] = 1;            findIsland(i-1,j);        }        if(i+1<m && map[i+1][j]=='1' && visit[i+1][j]==0){            visit[i+1][j] = 1;            findIsland(i+1,j);        }        if(j-1>=0 && map[i][j-1]=='1' && visit[i][j-1]==0){            visit[i][j-1] = 1;            findIsland(i,j-1);        }        if(j+1<n && map[i][j+1]=='1' && visit[i][j+1]==0){            visit[i][j+1] = 1;            findIsland(i,j+1);        }    }        public int numIslands(char[][] grid) {        m = grid.length;        if(m == 0){            return 0;        }        n = grid[0].length;        map = new char[m][n];        visit = new int[m][n];        for(int i=0;i<m;i++)            for(int j=0;j<n;j++)                map[i][j] = grid[i][j];                    int count = 0;                for(int i=0;i<m;i++)            for(int j=0;j<n;j++){                if(grid[i][j]=='1' && visit[i][j]==0){                    count++;                    findIsland(i,j);                }            }                        return count;    }}


0 0
原创粉丝点击