您的位置:首页 > 其它

LeetCode | 764. Largest Plus Sign中等偏难 二维数组找规律题

2018-01-18 17:56 477 查看
Ina 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the givenlist mines which are 0. What is the largest axis-aligned plus sign of 1s contained in the grid? Return theorder of the plus sign. If there is none, return 0.An"axis-aligned plus sign of 1s of order k" has some center grid[x][y] =1 along with 4 arms of length k-1 going up, down, left, and right, and made of 1s. This is demonstrated in thediagrams below. Note that there could be 0s or 1s beyond the arms of the plus sign,only the relevant area of the plus sign is checked for 1s.Examplesof Axis-Aligned Plus Signs of Order k:Order 1:
000
010
000
 
Order 2:
00000
00100
01110
00100
00000
 
Order 3:
0000000
0001000
0001000
0111110
0001000
0001000
0000000
Example1:Input: N = 5, mines = [[4, 2]]
Output: 2
Explanation:
11111
11111
11111
11111
11011
In the above grid, the largest plus sign can only be order2.  One of them is marked in bold.
Example2:Input: N = 2, mines = []
Output: 1
Explanation:
There is no plus sign of order 2, but there is of order 1.
Example3:Input: N = 1, mines = [[0, 0]]
Output: 0
Explanation:
There is no plus sign, so return 0.
Note:1.      N will be an integer in the range [1, 500].2.      mines will have length at most 5000.3.      mines[i] will be length 2 and consist of integers in the range [0, N-1].4.      (Additionally, programs submitted inC, C++, or C# will be judged with a slightly smaller time limit.)这题给你一个1和0组成的矩阵,问你这个矩阵里面最大的一个十字每条边有多长,
这题难到不难,就是非常的复杂,假如使用暴力解决,遍历矩阵里面的每一个数字,那么时间一定会超时,所以不能考虑暴力解决
好在这一题是有规律的,对于每一个1而言,按照从左到右,从上到下的顺序,搜索,每当找到一个1的时候,它离上方0,左边0,右边0,下面0的最短距离都能够按照规律由它上方,左边,的上一个1得到,具体规律在程序中有写到
按照这种规律能够节省很大的部分的时间
以后在做题的时候,当需要某个特定的数据结构的数组的时候记得去定义这样的结构体,合适的数据结构能够节省很大一部分的时间!class Solution {
public:
struct node
{
int left,right,up,down;
node(int left2 = 0, int right2 = 0, int up2 = 0, int down2 = 0)
{
left = left2;
right = right2;
up = up2;
down = down2;
}
};

int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {
vector<vector<int>> grid(N,vector<int> (N,1));
vector<vector<node>> rem(N, vector<node>(N, node()));

for(int i=0;i<mines.size();i++)
{
grid[mines[i][0]][mines[i][1]] = 0;
}
int k = 0;
int r, c;
r = grid.size(); c = grid[0].size();
for(int i=0;i<r;i++)
for (int j = 0; j < c; j++)
{
if (grid[i][j] == 1)
{
if (j==0) rem[i][j].left = 1;
else
{
rem[i][j].left = rem[i][j - 1].left + 1;
}
if (i==0) rem[i][j].up = 1;
else
{
rem[i][j].up = rem[i-1][j].up + 1;
}
if(j>0&&grid[i][j-1]!=0) rem[i][j].right = rem[i][j-1].right - 1;
else
{
int l = j;
while (l < c&&grid[i][l] == 1) l++;
rem[i][j].right = l - j;
}
if (i>0 && grid[i-1][j] != 0) rem[i][j].down = rem[i-1][j].down - 1;
else
{
int l = i;
while (l < r&&grid[l][j] == 1) l++;
rem[i][j].down = l - i;
}

k = max(k, min(rem[i][j].left, min(rem[i][j].up, min(rem[i][j].right,rem[i][j].down))));
}
}
return k;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二维矩阵