BFS:
1、空间是指数级别 大!!!
2、不会有爆栈的风险
3、最短、最小
DFS:
1、空间和深度成正比 小!!!
2、有爆栈的风险,比如树的深度最坏有1000000层
3、不能搜最短、最小
题目1:Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
/*
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x),left(NULL),right(NULL);
}
*/
class Solution{
public:
int minDepth(TreeNode* root){
if(!root) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if(!left||!right) return left+right+1;
return min(left,right)+1;
/*
if(root == nullptr) return 0;
if(root->left == nullptr) // 若左子树为空,则返回右子树的最小深度+1
{
return run(root->right)+1;
}
if(root->right == nullptr) // 若右子树为空,则返回左子树的最小深度+1
{
return run(root->left)+1;
}
// 左右子树都不为空时,取较小值
int leftDepth = run(root->left);
int rightDepth = run(root->right);
return (leftDepth<rightDepth)?(leftDepth+1):(rightDepth+1);
*/
}
}
题目2:给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。如下:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
思路:类似于图论的思想,求该题的解,可以用广度搜索的思想,每次搜索得到符合的答案,都能够从一个点转至另一个点,最后演变成从0点到n点的距离问题。
class Solution{
public:
int numSquares(int n){
queue<int> q;
vector<int> dist(n+1,INT_MAX);
q.push(0);
dist[0] = 0;
while(!q.empty()){
int t = q.front();
q.pop();
if(t == n) return dist[t];
for(int i=1;i*i+t<=n;i++){
int j = i*i+t;
if(dist[j]>dist[t]+1){
dist[j] = dist[t]+1;
q.push(j);
}
}
}
return 0;
}
}
题目:给定一个二维数组,并且给定起始的坐标,以及新的颜色,寻找出数组中连通块(同一种颜色/数字),并将其替换成新的颜色。
例如:1 1 1
1 1 0
1 0 1
---> 2 2 2
2 2 0
2 0 1
class Solution{
public:
vector<vector<int>> floodFill(vector<vector<int>> &image,int sr,int sc,int newColor){
if(image.empty()||image[0].empty()) return image;
int dx[4] = {-1,0,1,0},int dy[4] = {0,1,0,-1};//顺序是左上右下
int oldColor = image[sr][sc];
if(oldColor == newColor) return iamge;
image[sr][sc] = newColor;
for(int i=0;i<4;i++){
int x = sr + dx[i],int y = sc +dy[i];//进行方向的移动,顺序是左上右下
if(x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor)
floodFill(image,x,y,newColor);
}
return image;
}
}