dfs 基础题目总结
1.dfs 连通的水域大小
给一个矩阵从数字为0表示水域,不为0表示陆地,可以上下左右,对角线方向连通水域,返回一个数组,从小到大排列水域的大小。
class Solution {
public:
vector<int> pondSizes(vector<vector<int>> &land) {
int m= land.size();
int n = land[0].size();
vector<vector<int>> visited(m, vector<int>(n));
vector<int> res;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (land[i][j] == 0) {
int ret = dfs(i, j, land, visited);
if (ret != 0) res.push_back(ret);
}
}
}
sort(res.begin(), res.end());
return res;
}
int dfs(int row, int col, vector<vector<int>> &land, vector<vector<int>> &visited) {
if (row < 0 || col < 0 || row >= nr || col >= nc) return 0;
if (land[row][col] != 0) return 0;
if (visited[row][col] == 1) return 0;
visited[row][col] = 1;
auto dxs = {-1, 0, 1};
auto dys = {-1, 0, 1};
int ret = 1;
for (auto &dx : dxs) {
for (auto &dy:dys) {
if (dx == 0 && dy == 0) continue;
ret += dfs(row + dx, col + dy, land, visited);
}
}
return ret;
}
};
2.朋友圈
可以用并查集和dfs
朋友具有传递性,求朋友圈总数 m[i][j]=1表示i和j互为朋友,求朋友圈总数
解法:将矩阵看成邻接矩阵,求出无向连通图的个数:
M= [1 1 0 0 0 0
1 1 0 0 0 0
0 0 1 1 1 0
0 0 1 1 0 0
0 0 1 0 1 0
0 0 0 0 0 1]
void DFS(vector<vector<int>>& M,vector<int> &visit,int n){
visit[n]=1;
for(int j=0;j<M.size();++j)
if(M[n][j] && !visit[j])
DFS(M,visit,j);
}
int findCircleNum(vector<vector<int>>& M) {
int N=M.size();
vector<int> visit(M.size(),0);
int count=0;
for(int i=0;i<N;++i){
if(!visit[i]){
DFS(M,visit,i);
count++;
}
}
return count;
}
};
3.二叉树路径遍历,
class Solution {
public:
void const(TreeNode * root ,string out,vector<string> &res){
if(root!=nullptr){
out+=to_string(root->val);
if(root->left==nullptr&&root->right==nullptr)
res.push_back(out);
}
else { out+="->";
const(root->left,out,res);
const(root->right,out,res);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
const(root,"",res);
return res;
}
};
4.二叉树路径总和
和上面同样的方法;
struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode *node,int out,int &res){
if(node!=nullptr){
out=out*10+node->val;
if(node->left==nullptr&&node->right==nullptr){
res+=out;
}
else {
dfs(node->left,out,res);
dfs(node->right,out,res);
}
}
}
int sumNumbers(TreeNode* root) {
int res=0;
dfs(root,0,res);
return res;
}
};
5.从根节点到叶子节点路径和等于指定和
class Solution {
public:
void dfs(TreeNode *root,int &sum,int ac,vector<int> out,vector<vector<int>> &res){
if(root!=nullptr){
{ac+=root->val;out.push_back(root->val);
if(root->left==nullptr&&root->right==nullptr){
if(ac==sum) res.push_back(out);
}
else {
dfs(root->left,sum,ac,out,res);
dfs(root->right,sum,ac,out,res);
}
}
}}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
dfs(root,sum,0,{},res);
return res;
}
};
6.给一个矩阵返回一个矩阵 每个矩阵元素表示该数离0最近的位置数

浙公网安备 33010602011771号