1.岛屿最大面积
分析:
典型的dfs例题。我们从某一个1出发进行深搜,直到将其周围所有能访问到的1全部标记,并记录该岛屿的面积。接着从另一个未被标记的1出发,重复上述过程。
代码:
class Solution {
public:
int dfs(vector<vector<int>>& grid, int i, int j) {
int m = grid.size(), n = grid[0].size();
if(i < 0 || i >= m || j < 0 || j >= n) {
return 0;
}
if(grid[i][j] == 0) {
return 0;
}
grid[i][j] = 0;
return 1 + dfs(grid, i, j - 1) + dfs(grid, i, j + 1) + dfs(grid, i + 1, j) + dfs(grid, i - 1, j);
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int res = 0;
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[0].size(); j++) {
if(grid[i][j]) {
res = max(res, dfs(grid, i, j));
}
}
}
return res;
}
};
2.图像渲染
分析:
题目描述的是一种不断扩展的过程,由此联想到bfs。首先将初始位置入队,接着在队列不为空的情况下,坐标出队,并将其上下左右四个方向中满足条件的坐标点入队,重复上述过程。
代码:
class Solution {
private:
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
vector<vector<int>> res = image;
int m = res.size();
int n = res[0].size();
queue<pair<int, int>> que;
pair<int, int> s(sr, sc);
int oldColor = image[sr][sc];
if(oldColor == newColor) {
return res;
}
que.push(s);
while(!que.empty()) {
pair<int, int> t = que.front();
que.pop();
int x = t.first, y = t.second;
res[x][y] = newColor;
for(int i = 0; i < 4; i++) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if(xx >= 0 && xx < m && yy >= 0 && yy < n && res[xx][yy] == oldColor) {
pair<int, int> st(xx, yy);
que.push(st);
}
}
}
return res;
}
};
3.合并二叉树
分析:
递归。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(!root1) {
return root2;
}
if(!root2) {
return root1;
}
TreeNode* merge = new TreeNode(root1->val + root2->val);
merge->left = mergeTrees(root1->left, root2->left);
merge->right = mergeTrees(root1->right, root2->right);
return merge;
}
};