[Thousands of Algorithmic Cases] ⚡ Daily LeetCode clock-in ⚡ - 58. Perimeter of the island

📢 Preface

🚀 Algorithmic problems 🚀
  • 🌲 Typing an algorithmic problem every day is both a learning process and a sharing process 😜
  • 🌲 Tip: This column uses both C#and Java for problem solving programming languages
  • 🌲 To keep learning every day, let's work together to become the algorithmic God 🧐!
  • 🌲 Today is the 58th day of punch-in 🎈!
🚀 Algorithmic problems 🚀

🌲 Sample theme: perimeter of island

Given a two-dimensional grid map grid of row x col, where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.

The grids in the grid are connected horizontally and vertically (not diagonally). The entire grid is completely surrounded by water, but there happens to be one island (or one or more islands that are connected by grids representing land).

There is no lake on the island ("lake" means that the water is inside the island and not connected to the water around the island).
The lattice is a square with a side length of 1. The grid is rectangular and has a width and height of no more than 100. Calculate the perimeter of the island.

Example 1:

Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
 Explanation: Its perimeter is the 16 yellow edges in the picture above

Example 2:

Input: grid = [[1]]
Output: 4

Example 3:

Input: grid = [[1,0]]
Output: 4

Tips:

  • row == grid.length
  • col == grid[i].length
  • 1 <= row, col <= 100
  • grid[i][j] is 0 or 1

🌻 C#Method: Sorting

Use return nums.Sum() - nums.Min() * nums.Length; You can do that, but Sum will overflow

So modify it to the following code, just go through it once!

Code:

public class Solution {
    public int MinMoves(int[] nums) {
             int iSum = nums.Min() * nums.Length * -1;
            foreach (var num in nums)
            {
                iSum += num;
            }
            return iSum;
    }
}

results of enforcement

adopt
 Execution time: 156 ms,At all C# 53.85% of users were defeated in submission
 Memory consumption: 48.1 MB,At all C# 23.08% of users were defeated in submissions

🌻 Java Method One: Iteration

Idea Analysis

  • For each edge of a land grid, it is calculated as the perimeter of the island if and only if the edge is a grid boundary or if the other adjacent grid is water.

  • So we can traverse each land grid to see if its four directions are boundaries or waters.

  • If so, add the contribution of this edge (111) to the answer anstextit{ans} ANS.

Code:

class Solution {
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};

    public int islandPerimeter(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (grid[i][j] == 1) {
                    int cnt = 0;
                    for (int k = 0; k < 4; ++k) {
                        int tx = i + dx[k];
                        int ty = j + dy[k];
                        if (tx < 0 || tx >= n || ty < 0 || ty >= m || grid[tx][ty] == 0) {
                            cnt += 1;
                        }
                    }
                    ans += cnt;
                }
            }
        }
        return ans;
    }
}

results of enforcement

adopt
 Execution time:8 ms,At all Java  74 defeated in submission.95%Users
 Memory consumption: 40 MB,At all Java 43 beats in submission.71%Users

Complexity analysis

Time Complexity: O( nm ),among n Is the length of the array, k Is the difference between the maximum and minimum.
Spatial Complexity: O( 1) 

🌻 Java Method 2: Deep First Search

Idea Analysis

  • We can also change the method to depth-first search traversal, which extends to counting the perimeters of multiple islands.

  • It is important to note that the terrestrial grid is prevented from being repeatedly traversed in deep-first searches causing a dead cycle.

  • We need to mark the traversed land grid as traversed, and in the code below we set a value of 2 to the traversed land grid.

Code:

class Solution {
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};

    public int islandPerimeter(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (grid[i][j] == 1) {
                    ans += dfs(i, j, grid, n, m);
                }
            }
        }
        return ans;
    }

    public int dfs(int x, int y, int[][] grid, int n, int m) {
        if (x < 0 || x >= n || y < 0 || y >= m || grid[x][y] == 0) {
            return 1;
        }
        if (grid[x][y] == 2) {
            return 0;
        }
        grid[x][y] = 2;
        int res = 0;
        for (int i = 0; i < 4; ++i) {
            int tx = x + dx[i];
            int ty = y + dy[i];
            res += dfs(tx, ty, grid, n, m);
        }
        return res;
    }
}

results of enforcement

adopt
 Execution time:12 ms,At all Java  10 beats in submission.09%Users
 Memory consumption: 40.4 MB,At all Java 6 defeated in submission.29%Users

Complexity analysis

Time Complexity: O( nm )
Spatial Complexity: O( nm ) 

💬 summary

  • Today is the 58th day of punching!
  • This article uses two programming languages C#and Java to solve problems
  • Some methods are also referential, capitalized, and shared as you learn, thank the algorithmic guys again
  • That's the end of today's algorithmic sharing. Bye tomorrow!

Tags: Java Algorithm leetcode

Posted on Tue, 19 Oct 2021 13:34:38 -0400 by ozestretch