[Leetcode 200] Number of Islands

Source: Internet
Author: User

Title Link: 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 are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water. Example 1:11110110101100000000answer:1example 2:11000110000010000011answer:3 * */public class NumberOfIslands {//45/4  5 test Cases passed.//status:accepted//runtime:298 ms//submitted:0 minutes ago////time complexity O (n ^ 2), Space complexity O (1) public int        Numislands (char[][] grid) {int m = grid.length;        if (M = = 0) return 0;        int n = grid[0].length;        int islands = 0; for (int i = 0; i < m; i + +) {for (int j = 0; J < N; j + +) {if (grid[i][j] = = ' 1 ') {Islands + +;d fs (grid, I, j);    }}} return islands;     } public void Dfs (char[][] grid, int i, int j) {if (I < 0 | | i = = Grid.length | | J < 0 | | j = grid[0].length) return;//validation within the matrix range if (grid[i][j] = = ' 1 ') {grid[i][j] = ' 0 ';/marked as visited Dfs (grid, I-1, j);//Left DFS (grid, i + 1, j);//Right Dfs (grid, I, j-1);//DFS (grid, I, j + 1);//Next} }public static void Main (string[] args) {//TODO auto-generated method stub}}


[Leetcode 200] Number of Islands

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.