天池 在线编程 寻找比周围都大的点(模拟)

文章目录

1. 题目

https://tianchi.aliyun.com/oj/245679029019779851/254275128279634587

给一个n*m大小的矩阵,寻找矩阵中所有比邻居(上下左右,对角也算,不考虑边界就是8个咯)都严格大的点。
返回一个n*m大小的矩阵,如果原矩阵中的点比邻居都严格大,则该位置为1,反之为0。

1<=n,m<=100

示例
样例 1
输入:
1 2 3
4 5 8
9 7 0

输出:
0 0 0
0 0 1
1 0 0

2. 解题

  • 模拟,时间复杂度 O(mn)
class Solution {
   
   
public:
    /**
     * @param grid: a matrix
     * @return: Find all points that are strictly larger than their neighbors
     */
    vector<vector<int>> highpoints(vector<vector<int>> &grid) {
   
   
        // write your code here
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> ans(grid);
        vector<vector<int>> dir = {
   
   {
   
   1,0},{
   
   0,1},{
   
   -1,0},{
   
   0,-1},{
   
   1,1},{
   
   -1,-1},{
   
   1,-1},{
   
   -1,1}};
        for(int i = 0; i < m; i++) 
        {
   
   
            for(int j = 0; j < n; j++)
            {
   
   
                bool large = true;
                for(int k = 0; k < 8; k++)
                {
   
   
                    int nx = i+dir[k][0];
                    int ny = j+dir[k][1];
                    if(nx>=0 && nx < m && ny>=0 && ny < n && grid[i][j] <= grid[nx][ny])
                    {
   
   
                        large = false;
                        break;
                    }
                }
                ans[i][j] = int(large);
            }
        }
        return ans;
    }
};

100ms C++


我的CSDN博客地址 https://michael.blog.csdn.net/

长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
Michael阿明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章