第一题 模拟
https://leetcode-cn.com/problems/richest-customer-wealth/
- 思路
- 遍历每一行,求和
- 更新最大值
- 返回
int maximumWealth(vector<vector<int>>& accounts) {
int ret = INT_MIN;
for (auto &person : accounts) {
int sum = 0;
for (int n : person) {
sum += n;
}
ret = max(ret, sum);
}
return ret;
}
第二题 多元BFS(hot 200)
https://leetcode-cn.com/problems/walls-and-gates/
- 思路
- 从门的位置作为起点,进行搜索
- 因为门的位置很多,我们以所有门的位置为起点
- 依次进入队列搜索,搜索相邻的四个位置,值为当前值+1
- 仅对INT_MAX的位置进行搜索,其他位置不是已经搜索过就是墙
void wallsAndGates(vector<vector<int>>& rooms) {
if (rooms.empty())
return;
int m = rooms.size(), n = rooms[0].size();
queue<pair<int, int>> cur;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (rooms[i][j] == 0) {
cur.push({i, j});
}
}
}
int dirs[][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
while (!cur.empty()) {
int x = cur.front().first, y = cur.front().second;
cur.pop();
for (int i = 0; i < 4; ++i) {
int nextX = x + dirs[i][0], nextY = y + dirs[i][1];
if(nextX >= 0 && nextY >= 0 && nextX < m && nextY < n){
if (rooms[nextX][nextY] == INT_MAX) {
rooms[nextX][nextY] = rooms[x][y] + 1;
cur.push({nextX, nextY});
}
}
}
}
return;
}