BFS算法的介绍和使用(上)

BFS在算法中有极高的应用价值,我们也从这从这篇文章中来学习如何更好地使用!!!

class Solution {

public:

const int dx4 = {1, 0, 0, -1};

const int dy4 = {0, 1, -1, 0};

vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {

int currColor = imagesrsc;

if (currColor == color) {

return image;

}

int n = image.size(), m = image0.size();

queue<pair<int, int>> que;

que.emplace(sr, sc);

imagesrsc = color;

while (!que.empty()) {

int x = que.front().first, y = que.front().second;

que.pop();

for (int i = 0; i < 4; i++) {

int mx = x + dxi, my = y + dyi;

if (mx >= 0 && mx < n && my >= 0 && my < m && imagemxmy == currColor) {

que.emplace(mx, my);

imagemxmy = color;

}

}

}

return image;

}

};

class Solution {

public:

int dx4 = {0, 0, 1, -1};

int dy4 = {1, -1, 0, 0};

bool ret301301;

int m, n;

int numIslands(vector<vector<char>>& grid) {

int result = 0;

n = grid.size();

if (n == 0) return 0;

m = grid0.size();

// 初始化ret数组

for (int i = 0; i < n; i++) {

for (int j = 0; j < m; j++) {

retij = false;

}

}

for (int i = 0; i < n; i++) {

for (int j = 0; j < m; j++) {

if (gridij == '1' && !retij) {

result++;

bfs(grid, i, j);

}

}

}

return result;

}

void bfs(vector<vector<char>>& grid, int i, int j) {

queue<pair<int, int>> q;

q.push({i, j});

retij = true; // 标记起点

while (!q.empty()) {

auto a, b = q.front();

q.pop();

for (int k = 0; k < 4; k++) { // 修复:k++

int x = dxk + a, y = dyk + b;

if (x >= 0 && x < n && y >= 0 && y < m &&

gridxy == '1' && !retxy) {

q.push({x, y});

retxy = true;

}

}

}

}

};

class Solution {

public:

int dx4={1,-1,0,0};

int dy4={0,0,1,-1};

int m,n;

bool a5151;

int maxAreaOfIsland(vector<vector<int>>& nums) {

m=nums.size(),n=nums0.size();

int ret=0;

for(int i=0;i<m;i++){

for(int j=0;j<n;j++){

if(numsij==1&&!aij){

ret = max(ret, bfs(nums, i, j));

}

}

}

return ret;

}

int bfs(vector<vector<int>>& nums,int i,int j){

queue<pair<int,int>> q;

q.push({i,j});

aij=true;

int ret=1;

while(q.size()){

auto b,c=q.front();

q.pop();

for(int k=0;k<4;k++){

int x=b+dxk,y=c+dyk;

if(x>=0&&x<m&&y>=0&&y<n&&numsxy==1&&!axy){

ret++;

axy=true;

q.push({x,y});

}

}

}

return ret;

}

};

复制代码
class Solution {
public:
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    int m,n;

    void solve(vector<vector<char>>& board) {
        m=board.size(),n=board[0].size();
        for(int i=0;i<n;i++){
            if(board[0][i]=='O') bfs(board,0,i);
            if(board[m-1][i]=='O') bfs(board,m-1,i);
        }
        for(int i=0;i<m;i++){
            if(board[i][0]=='O') bfs(board,i,0);
            if(board[i][n-1]=='O') bfs(board,i,n-1);
        }
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(board[i][j]=='O') board[i][j]='X';
                else if(board[i][j]=='.') board[i][j]='O';
            }
        }
    }

    void bfs(vector<vector<char>>& nums,int i,int j){
        queue<pair<int,int>> q;
        q.push({i,j});
        nums[i][j]='.';
        while(q.size()){
            auto [a,b]=q.front();
            q.pop();
            for(int k=0;k<4;k++){
                int x=a+dx[k],y=b+dy[k];
                if(x>=0&&x<m&&y>=0&&y<n&&nums[x][y]=='O'){
                    nums[x][y]='.';
                    q.push({x,y});
                }
            }
        }
    }
};

class Solution {

public:

int dx4={0,0,1,-1};

int dy4={1,-1,0,0};

int nearestExit(vector<vector<char>>& nums, vector<int>& e) {

int n=nums.size(),m=nums0.size();

bool vnm;

memset(v,0,sizeof (v));

queue<pair<int,int>> q;

q.push({e0,e1});

ve\[0]e\[1]=true;

int step=0;

while(q.size()){

step++;

int sz=q.size();

for(int i=0;i<sz;i++){

auto a,b=q.front();

q.pop();

for(int k=0;k<4;k++){

int x=a+dxk,y=dyk+b;

if(x>=0&&x<n&&y>=0&&y<m&&numsxy=='.'&&!vxy){

if(x == 0 || x == n - 1 || y == 0 || y == m - 1) return step;

vxy=true;

q.push({x,y});

}

}

}

}

return -1;

}

};

z注:memset的作用是将整个数组清零

class Solution {

public:

int minMutation(string startGene, string endGene, vector<string>& bank) {

unordered_set<string> vis;

unordered_set<string> hash(bank.begin(),bank.end());

string change="ACGT";

if(startGene==endGene) return 0;

if(!hash.count(endGene)) return -1;

queue<string> q;

q.push(startGene);

vis.insert(startGene);

int ret=0;

while(q.size()){

ret++;

int sz=q.size();

while(sz--){

string t=q.front();

q.pop();

for(int i=0;i<8;i++){

string tmp=t;

for(int j=0;j<4;j++){

tmpi=changej;

if(hash.count(tmp)&&!vis.count(tmp)){

if(tmp==endGene) return ret;

q.push(tmp);

vis.insert(tmp);

}

}

}

}

}

return -1;

}

};

class Solution {

public:

int ladderLength(string beginword, string endword, vector<string>& wordlist) {

unordered_set<string> hash(wordlist.begin(),wordlist.end());

unordered_set<string> vis;

if(!hash.count(endword)) return 0;

int step=1;

int n=beginword.size();

queue<string> q;

q.push(beginword);

vis.insert(beginword);

while(q.size()){

int sz=q.size();

step++;

while(sz--){

string t=q.front();

q.pop();

for(int i=0;i<n;i++){

string tmp=t;

for(char ch='a';ch<='z';ch++){

tmpi=ch;

if(hash.count(tmp)&&!vis.count(tmp)){

if(tmp==endword) return step;

vis.insert(tmp);

q.push(tmp);

}

}

}

}

}

return 0;

}

};

class Solution {

public:

int m, n;

int dx4 = {0, 0, 1, -1};

int dy4 = {1, -1, 0, 0};

int bfs(vector<vector<int>>& forest, int sx, int sy, int tx, int ty) {

if (sx == tx && sy == ty) return 0;

vector<vector<bool>> vis(m, vector<bool>(n, false));

queue<pair<int, int>> q;

q.push({sx, sy});

vissxsy = true;

int step = 0;

while (!q.empty()) {

step++;

int sz = q.size();

while (sz--) {

auto x, y = q.front();

q.pop();

for (int i = 0; i < 4; i++) {

int nx = x + dxi, ny = y + dyi;

if (nx >= 0 && nx < m && ny >= 0 && ny < n && forestnxny != 0 && !visnxny) {

if (nx == tx && ny == ty) return step;

q.push({nx, ny});

visnxny = true;

}

}

}

}

return -1;

}

int cutOffTree(vector<vector<int>>& forest) {

m = forest.size();

n = forest0.size();

// 收集所有树的位置和高度

vector<tuple<int, int, int>> trees; // (height, x, y)

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

if (forestij > 1) {

trees.emplace_back(forestij, i, j);

}

}

}

// 按高度排序

sort(trees.begin(), trees.end());

int sx = 0, sy = 0;

int totalSteps = 0;

for (auto& h, tx, ty : trees) {

int steps = bfs(forest, sx, sy, tx, ty);

if (steps == -1) return -1;

totalSteps += steps;

sx = tx;

sy = ty;

}

return totalSteps;

}

};

相关推荐
人道领域29 分钟前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法
QiLinkOS1 小时前
【从实验室到商业战场:发明专利如何重塑科技与企业的共生生态】
大数据·c语言·数据结构·c++·人工智能·单片机·算法
小白兔奶糖ovo2 小时前
【Leetcode】231. 2的幂
linux·算法·leetcode
xiaoxiaoxiaolll2 小时前
《Light: Science & Applications》合并BIC实现80倍阈值单模运行:超紧凑光子晶体激光器新突破
人工智能·算法·机器学习
Peter·Pan爱编程2 小时前
14. Lambda 表达式:随手可写的函数对象
c++·算法·ai编程
-To be number.wan2 小时前
算法日记 | 暴力枚举
学习·算法
s_w.h3 小时前
【 linux 】动静态库的制作
linux·运维·服务器·算法·bash
过期动态3 小时前
【LeetCode 热题 100】接雨水
java·数据结构·算法·leetcode·职场和发展
春日见3 小时前
5分钟入门强化学习之动态规划算法与实现
大数据·人工智能·python·算法·机器学习·计算机视觉
scx_link4 小时前
线性回归的总结:
算法·机器学习·线性回归