Number of Islands LeetCode Programming Solutions | LeetCode Problem Solutions in C++, Java, & Python [💯Correct]

LeetCode Problem | LeetCode Problems For Beginners | LeetCode Problems & Solutions | Improve Problem Solving Skills | LeetCode Problems Java | LeetCode Solutions in C++

Hello Programmers/Coders, Today we are going to share solutions to the Programming problems of LeetCode Solutions in C++, Java, & Python. At Each Problem with Successful submission with all Test Cases Passed, you will get a score or marks and LeetCode Coins. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for the Number of Islands in C++, Java & Python-LeetCode problem. We are providing the correct and tested solutions to coding problems present on LeetCode. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

About LeetCode

LeetCode is one of the most well-known online judge platforms to help you enhance your skills, expand your knowledge and prepare for technical interviews. 

LeetCode is for software engineers who are looking to practice technical questions and advance their skills. Mastering the questions in each level on LeetCode is a good way to prepare for technical interviews and keep your skills sharp. They also have a repository of solutions with the reasoning behind each step.

LeetCode has over 1,900 questions for you to practice, covering many different programming concepts. Every coding problem has a classification of either EasyMedium, or Hard.

LeetCode problems focus on algorithms and data structures. Here is some topic you can find problems on LeetCode:

  • Mathematics/Basic Logical Based Questions
  • Arrays
  • Strings
  • Hash Table
  • Dynamic Programming
  • Stack & Queue
  • Trees & Graphs
  • Greedy Algorithms
  • Breadth-First Search
  • Depth-First Search
  • Sorting & Searching
  • BST (Binary Search Tree)
  • Database
  • Linked List
  • Recursion, etc.

Leetcode has a huge number of test cases and questions from interviews too like Google, Amazon, Microsoft, Facebook, Adobe, Oracle, Linkedin, Goldman Sachs, etc. LeetCode helps you in getting a job in Top MNCs. To crack FAANG Companies, LeetCode problems can help you in building your logic.

Link for the ProblemNumber of Islands– LeetCode Problem

Number of Islands– LeetCode Problem


Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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:

Input: grid = [
Output: 1

Example 2:

Input: grid = [
Output: 3


  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.
Number of Islands– LeetCode Solutions
Number of Islands Solution in C++:
class Solution {
  int numIslands(vector<vector<char>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    const vector<int> dirs{0, 1, 0, -1, 0};
    int ans = 0;

    auto bfs = [&](int r, int c) {
      queue<pair<int, int>> q{{{r, c}}};
      grid[r][c] = '2';  // mark '2' as visited
      while (!q.empty()) {
        const auto [i, j] = q.front();
        for (int k = 0; k < 4; ++k) {
          const int x = i + dirs[k];
          const int y = j + dirs[k + 1];
          if (x < 0 || x == m || y < 0 || y == n)
          if (grid[x][y] != '1')
          q.emplace(x, y);
          grid[x][y] = '2';  // mark '2' as visited

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j] == '1') {
          bfs(i, j);

    return ans;
Number of Islands Solution in Java:
class Solution {
  public int numIslands(char[][] grid) {
    int ans = 0;

    for (int i = 0; i < grid.length; ++i)
      for (int j = 0; j < grid[0].length; ++j)
        if (grid[i][j] == '1') {
          dfs(grid, i, j);

    return ans;

  private void dfs(char[][] grid, int i, int j) {
    if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)
    if (grid[i][j] != '1')

    grid[i][j] = '2'; // mark '2' as visited
    dfs(grid, i + 1, j);
    dfs(grid, i - 1, j);
    dfs(grid, i, j + 1);
    dfs(grid, i, j - 1);
Number of Islands Solution in Python:
class Solution:
  def numIslands(self, grid: List[List[str]]) -> int:
    m = len(grid)
    n = len(grid[0])
    dirs = [0, 1, 0, -1, 0]

    def bfs(r, c):
      q = deque([(r, c)])
      grid[r][c] = '2'  # mark '2' as visited
      while q:
        i, j = q.popleft()
        for k in range(4):
          x = i + dirs[k]
          y = j + dirs[k + 1]
          if x < 0 or x == m or y < 0 or y == n:
          if grid[x][y] != '1':
          q.append((x, y))
          grid[x][y] = '2'  # mark '2' as visited

    ans = 0

    for i in range(m):
      for j in range(n):
        if grid[i][j] == '1':
          bfs(i, j)
          ans += 1

    return ans

25 thoughts on “Number of Islands LeetCode Programming Solutions | LeetCode Problem Solutions in C++, Java, & Python [💯Correct]”

  1. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what youre talking about, why throw away your intelligence on just posting videos to your weblog when you could be giving us something informative to read?

  2. Wow, amazing weblog structure! How lengthy have you ever been running a blog for? you made running a blog look easy. The entire look of your web site is magnificent, as well as the content material!

  3. Thank you for another fantastic post. Where else could anyone get that kind of information in such an ideal way of writing? I’ve a presentation next week, and I’m on the look for such information.

  4. What i do not realize is if truth be told how you are no longer actually a lot more smartly-preferred than you may be right now. You’re very intelligent. You recognize therefore significantly in the case of this matter, made me in my view believe it from a lot of numerous angles. Its like women and men aren’t fascinated until it?¦s one thing to accomplish with Girl gaga! Your personal stuffs great. Always handle it up!

  5. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular you express are really awesome. Hope you will right some more posts.

  6. I will immediately grab your rss feed as I can not in finding your email subscription hyperlink or newsletter service. Do you’ve any? Please allow me recognize so that I may subscribe. Thanks.

  7. I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to know where u got this from. thanks

  8. I have recently started a site, the info you offer on this web site has helped me tremendously. Thanks for all of your time & work. “‘Tis our true policy to steer clear of permanent alliances with any portion of the foreign world.” by George Washington.

  9. I discovered your blog site on google and check a few of your early posts. Continue to keep up the very good operate. I just additional up your RSS feed to my MSN News Reader. Seeking forward to reading more from you later on!…

  10. Howdy just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Internet explorer. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the issue solved soon. Thanks

  11. This is really interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your magnificent post. Also, I’ve shared your website in my social networks!

  12. I’d need to check with you here. Which isn’t something I normally do! I enjoy reading a submit that can make people think. Also, thanks for allowing me to remark!

  13. Thanks, I have recently been looking for info approximately this topic for a while and yours is the greatest I’ve found out so far. But, what in regards to the bottom line? Are you certain concerning the source?

  14. I keep listening to the news bulletin lecture about receiving free online grant applications so I have been looking around for the finest site to get one. Could you tell me please, where could i find some?


Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock