《算法集训传送门》
?引言
铭记于心 | ||
---|---|---|
?✨?我唯一知道的,便是我一无所知?✨? |
? ❄️我们的算法之路❄️?
众所周知,作为一名合格的程序员,算法 能力 是不可获缺的,并且在算法学习的过程中我们总是能感受到算法的✨魅力✨。
☀️?短短几行代码,凝聚无数前人智慧;一个普通循环,即是解题之眼?☀️
?二分,?贪心,?并查集,?二叉树,?图论,?深度优先搜索(dfs),?宽度优先搜索(bfs),?数论,?动态规划等等, 路漫漫其修远兮,吾将上下而求索! 希望在此集训中与大家共同进步,有所收获!!!???
今日主题:深度优先搜索
?⭐️第一题?
✨题目
2331. 计算布尔二叉树的值 - 力扣(LeetCode)
✨代码:
/**
* 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 {
bool isLeaf(TreeNode* T){
if(!T->left && !T->right){
return T->val;
}
if(T->val == 2){
return isLeaf(T->left)||isLeaf(T->right);
}
return isLeaf(T->left)&&isLeaf(T->right);
}
public:
bool evaluateTree(TreeNode* root) {
return isLeaf(root);
}
};
?⭐️第二题?
✨题目
Loading Question… - 力扣(LeetCode)
✨代码:
class Solution {
int flag = 0;
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
if(!root1 && !root2){
return true;
}
if(!root1 && root2){
return false;
}
if(root1 && !root2){
return false;
}
if(root1->val != root2->val){
return false;
}
return( flipEquiv(root1->left,root2->left)&&flipEquiv(root1->right,root2->right) )||
( flipEquiv(root1->left,root2->right)&&flipEquiv(root1->right,root2->left) );
}
};
?⭐️第三题?
✨题目
✨代码:
class Solution {
public int[][] findFarmland(int[][] land) {
ArrayList<int[]> res = new ArrayList<>();
for (int r = 0 ; r < land.length ; r++) {
for (int c = 0 ; c < land[0].length ; c++) {
if (land[r][c] == 1) {
// 判断是不是左上角
if (c-1 >= 0 && land[r][c-1] == 1 || r-1 >= 0 && land[r-1][c] == 1) {
continue;
}
// 判断范围
int rr = r;
for ( ; rr < land.length && land[rr][c] == 1 ; rr++) ;
int cc = c;
for ( ; cc < land[0].length && land[r][cc] == 1; cc++) ;
res.add(new int[]{r,c,rr-1,cc-1});
}
}
}
return res.toArray(new int[0][]);
}
}
?写在最后?:
相信大家对今天的集训内容的理解与以往已经有很大不同了吧,或许也感受到了算法的魅力,当然这是一定的,路漫漫其修远兮,吾将上下而求索!伙伴们,明天见!???