• leetcode 463. Island Perimeter


    You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.

    Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

    The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

    Example:

    Input:
    [[0,1,0,0],
     [1,1,1,0],
     [0,1,0,0],
     [1,1,0,0]]
    
    Output: 16
    
    Explanation: The perimeter is the 16 yellow stripes in the image below:
    
    

    题目大意:求陆地的周长

    思路一:一个land四个边,四个方向每有一个相邻的land,边少一。

     1 int islandPerimeter(vector<vector<int>>& grid) {
     2         int cnt = 0;
     3         int m = grid.size();
     4         if (m == 0)
     5             return 0;
     6         int n = grid[0].size();
     7         int dx[4] = {-1, 0, 1, 0};
     8         int dy[4] = {0, 1, 0, -1};
     9         for (int i = 0; i < m; ++i) {
    10             for (int j = 0; j < n; ++j) {
    11                 if (grid[i][j] == 1) {
    12                     cnt += 4;
    13                     for (int k = 0; k < 4; ++k) {
    14                         int newx = i + dx[k];
    15                         int newy = j + dy[k];
    16                         if (newx >= 0 && newx < m && newy >= 0 && newy < n && grid[newx][newy] == 1) {
    17                             --cnt;
    18                         }
    19                     }
    20                 }
    21             }
    22         }
    23         return cnt;
    24     }

    问题:每个是1的land大概访问了4次。

    思路二:

  • 相关阅读:
    socket.io笔记
    node express+socket.io实现聊天室
    socket.io中 connect与connection的区别
    css clip-path的polygon属性绘制多边形
    vue 3.0
    angular
    项目总结61:IDEA远程调试linux下的tomcat
    Java深入学习28:Redisson分布式锁的使用
    Java深入学习27:Java反射
    Java深入学习28:Runnable和Callable
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11551358.html
Copyright © 2020-2023  润新知