Skip to content

Commit d72b0c5

Browse files
authored
Update 803.Bricks-Falling-When-Hit_DFS.cpp
1 parent 88859de commit d72b0c5

File tree

1 file changed

+17
-32
lines changed

1 file changed

+17
-32
lines changed
Lines changed: 17 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,46 @@
11
class Solution {
22
vector<vector<int>>visited; // 1: land, -1 : erased, 2 : connected
3-
vector<pair<int,int>>dir;
3+
vector<pair<int,int>>dir{{1,0},{-1,0},{0,1},{0,-1}};
4+
int m,n;
45
public:
56
vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits)
67
{
7-
int m = grid.size();
8-
int n = grid[0].size();
9-
dir = {{1,0},{-1,0},{0,1},{0,-1}};
10-
8+
m = grid.size();
9+
n = grid[0].size();
10+
1111
visited = grid;
1212
for (auto point:hits)
1313
visited[point[0]][point[1]] *= -1;
1414

1515
for (int j=0; j<n; j++)
1616
if (visited[0][j]==1)
17-
{
18-
int num = 0;
19-
dfs(0,j,num);
20-
}
17+
dfs(0,j);
2118

2219
vector<int>ret;
2320
reverse(hits.begin(),hits.end());
2421
for (auto point:hits)
2522
{
26-
int i = point[0];
27-
int j = point[1];
28-
23+
int i = point[0], j = point[1];
2924
if (visited[i][j]!=-1)
3025
{
3126
ret.push_back(0);
3227
continue;
3328
}
34-
bool find = (i==0);
29+
bool connectRoof = (i==0);
3530
for (int k=0; k<4; k++)
3631
{
3732
int x = i+dir[k].first;
3833
int y = j+dir[k].second;
39-
if (!isValid(x,y)) continue;
34+
if (x<0||x>=m||y<0||y>=n) continue;
4035
if (visited[x][y]==2)
4136
{
42-
find = true;
37+
connectRoof = true;
4338
break;
4439
}
4540
}
4641

47-
if (find)
48-
{
49-
int num = -1;
50-
dfs(i,j,num);
51-
ret.push_back(num);
52-
}
42+
if (connectRoof)
43+
ret.push_back(dfs(i,j-1);
5344
else
5445
{
5546
visited[i][j] = 1;
@@ -61,24 +52,18 @@ class Solution {
6152
return ret;
6253
}
6354

64-
bool isValid(int x, int y)
65-
{
66-
int m = visited.size();
67-
int n = visited[0].size();
68-
return !(x<0||x>=m||y<0||y>=n);
69-
}
70-
71-
void dfs(int i, int j, int &num)
55+
int dfs(int i, int j)
7256
{
7357
visited[i][j] = 2;
74-
num++;
58+
int count = 1;
7559
for (int k=0; k<4; k++)
7660
{
7761
int x = i+dir[k].first;
7862
int y = j+dir[k].second;
79-
if (!isValid(x,y)) continue;
63+
if (x<0||x>=m||y<0||y>=n) continue;
8064
if (visited[x][y]==1)
81-
dfs(x,y,num);
65+
count += dfs(x,y);
8266
}
67+
return count;
8368
}
8469
};

0 commit comments

Comments
 (0)