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阿明),一起加油、一起學習進步!