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

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

class Solution {

public:

const int dx[4] = {1, 0, 0, -1};

const int dy[4] = {0, 1, -1, 0};

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

int currColor = image[sr][sc];

if (currColor == color) {

return image;

}

int n = image.size(), m = image[0].size();

queue<pair<int, int>> que;

que.emplace(sr, sc);

image[sr][sc] = 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 + dx[i], my = y + dy[i];

if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {

que.emplace(mx, my);

image[mx][my] = color;

}

}

}

return image;

}

};

class Solution {

public:

int dx[4] = {0, 0, 1, -1};

int dy[4] = {1, -1, 0, 0};

bool ret[301][301];

int m, n;

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

int result = 0;

n = grid.size();

if (n == 0) return 0;

m = grid[0].size();

// 初始化ret数组

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

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

ret[i][j] = false;

}

}

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

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

if (grid[i][j] == '1' && !ret[i][j]) {

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});

ret[i][j] = true; // 标记起点

while (!q.empty()) {

auto [a, b] = q.front();

q.pop();

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

int x = dx[k] + a, y = dy[k] + b;

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

grid[x][y] == '1' && !ret[x][y]) {

q.push({x, y});

ret[x][y] = true;

}

}

}

}

};

class Solution {

public:

int dx[4]={1,-1,0,0};

int dy[4]={0,0,1,-1};

int m,n;

bool a[51][51];

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

m=nums.size(),n=nums[0].size();

int ret=0;

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

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

if(nums[i][j]==1&&!a[i][j]){

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});

a[i][j]=true;

int ret=1;

while(q.size()){

auto [b,c]=q.front();

q.pop();

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

int x=b+dx[k],y=c+dy[k];

if(x>=0&&x<m&&y>=0&&y<n&&nums[x][y]==1&&!a[x][y]){

ret++;

a[x][y]=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 dx[4]={0,0,1,-1};

int dy[4]={1,-1,0,0};

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

int n=nums.size(),m=nums[0].size();

bool v[n][m];

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

queue<pair<int,int>> q;

q.push({e[0],e[1]});

v[e[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+dx[k],y=dy[k]+b;

if(x>=0&&x<n&&y>=0&&y<m&&nums[x][y]=='.'&&!v[x][y]){

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

v[x][y]=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++){

tmp[i]=change[j];

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++){

tmp[i]=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 dx[4] = {0, 0, 1, -1};

int dy[4] = {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});

vis[sx][sy] = 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 + dx[i], ny = y + dy[i];

if (nx >= 0 && nx < m && ny >= 0 && ny < n && forest[nx][ny] != 0 && !vis[nx][ny]) {

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

q.push({nx, ny});

vis[nx][ny] = true;

}

}

}

}

return -1;

}

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

m = forest.size();

n = forest[0].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 (forest[i][j] > 1) {

trees.emplace_back(forest[i][j], 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;

}

};

相关推荐
sonnet-10292 小时前
堆排序算法
java·c语言·开发语言·数据结构·python·算法·排序算法
我是咸鱼不闲呀2 小时前
力扣Hot100系列24(Java)——[回溯]总结(下)(括号生成,单词搜索,分割回文串)
java·算法·leetcode
tankeven2 小时前
HJ150 全排列
c++·算法
Q741_1472 小时前
每日一题 力扣 2946. 循环移位后的矩阵相似检查 力扣 155. 最小栈 数学 数组 模拟 C++ 题解
c++·算法·leetcode·矩阵·模拟·数组·
handsomethefirst2 小时前
【算法与数据结构】【面试经典150题】【题41-题45】
数据结构·算法·leetcode
2301_810160952 小时前
C++中的状态模式
开发语言·c++·算法
xrgs_shz2 小时前
图像的点运算(线性点运算和非线性点运算)
人工智能·算法·机器学习
qq_466302452 小时前
vs2022 mn矩阵运算 加减乘除
c++·算法·矩阵
sin°θ_陈2 小时前
前馈式3D Gaussian Splatting 研究地图(总览篇):解构七大路线,梳理方法谱系,看懂关键分歧与未来趋势
论文阅读·深度学习·算法·3d·aigc·空间计算·3dgs