标签:color == boa ref imu 二叉树 ini 专题 public
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
关键在于知道f(root)=min(f(left),f(right))+1这个表达式
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;
}
};
https://leetcode-cn.com/problems/perfect-squares/
经典BFS
class Solution {
public:
typedef struct {
int num;
int temp;
}Num;
int numSquares(int n) {
queue<Num> q;
Num q1,q2;
q1.num=0;
q1.temp=0;
int vis[10005]={0};
vis[0]=1;
q.push(q1);
while(!q.empty()){
q1=q.front();
q.pop();
if(q1.num==n) return q1.temp;
int x=q1.num;
for(int i=1;x+i*i<=n;i++){
int j=x+i*i;
if(!vis[j]){
q2.num=j;
q2.temp=q1.temp+1;
vis[j]=1;
q.push(q2);
}
}
}
return 0;
}
};
https://leetcode-cn.com/problems/flood-fill/
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,-1,0,0},dy[4]={0,0,1,-1};
int old=image[sr][sc];
if(old==newColor){
//重新走了已经遍历的地方
return image;
}
image[sr][sc]=newColor;
for(int i=0;i<4;i++){
int x=sr+dx[i],y=sc+dy[i];
if(x>=0 && x<image.size() && y>=0 && y<image[0].size() && image[x][y]==old){
floodFill(image,x,y,newColor);
}
}
return image;
}
};
https://leetcode-cn.com/problems/number-of-islands/
class Solution {
public:
int vis[305][305]={0};
int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
void dfs(int x,int y,vector<vector<char>>& grid){
for(int i=0;i<4;i++){
int nx=x+dx[i],ny=y+dy[i];
if(nx>=0 && nx<grid.size() && ny>=0 && ny<grid[0].size() && !vis[nx][ny] && grid[nx][ny]==‘1‘){
grid[nx][ny]=‘0‘;
vis[nx][ny]=1;
dfs(nx,ny,grid);
}
}
}
int numIslands(vector<vector<char>>& grid) {
int ans=0;
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[0].size();j++){
if(grid[i][j]==‘1‘){
grid[i][j]=‘0‘;
vis[i][j]=1;
ans++;
dfs(i,j,grid);
}
}
}
return ans;
}
};
https://leetcode-cn.com/problems/surrounded-regions/
从边界的O出发DFS,所有没被打上标记的即被包围的
class Solution {
public:
int vis[205][205]={0};
int dx[4]={0,0,1,-1},dy[4]={1,-1,0,0};
void dfs(int x,int y,vector<vector<char>>& board){
int n=board.size(),m=board[0].size();
for(int i=0;i<4;i++){
int nx=x+dx[i],ny=y+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<m && !vis[nx][ny] && board[nx][ny]==‘O‘){
vis[nx][ny]=1;
dfs(nx,ny,board);
}
}
}
void solve(vector<vector<char>>& board) {
if(board.empty() || board[0].empty()) return ;
int n=board.size(),m=board[0].size();
for(int i=0;i<n;i++){
//扫描最左边和最右边
if(board[i][0]==‘O‘){
vis[i][0]=1;
dfs(i,0,board);
}
if(board[i][m-1]==‘O‘){
vis[i][m-1]=1;
dfs(i,m-1,board);
}
}
for(int j=0;j<m;j++){
//扫描最上面和最下面
if(board[0][j]==‘O‘){
vis[0][j]=1;
dfs(0,j,board);
}
if(board[n-1][j]==‘O‘){
vis[n-1][j]=1;
dfs(n-1,j,board);
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!vis[i][j]){
board[i][j]=‘X‘;
}
}
}
}
};
标签:color == boa ref imu 二叉树 ini 专题 public
原文地址:https://www.cnblogs.com/OfflineBoy/p/14532899.html