代码随想录leetcode200题之图论

目录

  • [1 介绍](#1 介绍)
  • [2 训练](#2 训练)
  • [3 参考](#3 参考)

1 介绍

本博客用来记录代码随想录leetcode200题之图论相关题目。

2 训练

题目198. 所有可达路径

解题思路:有向图,dfs(fa, node)

C++代码如下,

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

int n, m;
unordered_map<int,vector<int>> g;
vector<int> cur;
bool has_path = false;

void dfs(int fa, int node) {
    if (!cur.empty() && cur.back() == n) {
        has_path = true;
        for (int i = 0; i+1 < cur.size(); ++i) cout << cur[i] << " ";
        cout << cur.back() << endl;
        return;
    }
    for (auto x : g[node]) {
        if (x != fa) {
            cur.emplace_back(x);
            dfs(node, x);
            cur.pop_back();
        }
    }
    return;
}

int main() {
    g.clear();
    cur.clear();    
    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int a, b;
        cin >> a >> b;
        g[a].emplace_back(b);
    }
    cur.emplace_back(1);
    dfs(-1, 1);
    if (has_path == false) cout << "-1" << endl;
    return 0;
}

python3代码如下,

py 复制代码
import collections 

has_path = False 
g = collections.defaultdict(list)
cur = []
s = input()
n, m = map(int, s.split())
for i in range(m):
    s = input()
    a, b = map(int, s.split())
    g[a].append(b)

def dfs(fa: int, node: int, cur: list) -> None:
    global has_path
    if len(cur) > 0 and cur[-1] == n:
        newcur = [str(x) for x in cur]
        res = " ".join(newcur)
        print(res)
        has_path = True 
        return 
    for x in g[node]:
        if x != fa:
            cur.append(x)
            dfs(node, x, cur)
            del cur[-1]
    return

cur.append(1)
dfs(-1, 1, cur)
if has_path == False:
    print(-1)

题目299. 岛屿数量

解题思路:

C++代码如下,

cpp 复制代码
//dfs版本
#include <bits/stdc++.h>

using namespace std;

const int N = 60;
int n, m;
int g[N][N];
bool st[N][N];

void dfs(int i, int j) {
    if (i < 0 || i >= n || j < 0 || j >= m) return;
    if (st[i][j]) return;
    if (g[i][j] == 0) return;
    st[i][j] = true;
    dfs(i+1,j);
    dfs(i-1,j);
    dfs(i,j+1);
    dfs(i,j-1);
    return;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> g[i][j];
        }
    }
    
    memset(st, 0, sizeof st);
    int res = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (g[i][j] == 1 && st[i][j] == false) {
                dfs(i,j);
                res += 1;
            }
        }
    }
    
    cout << res << endl;

    return 0;    
}
cpp 复制代码
//bfs版本
#include <bits/stdc++.h>

using namespace std;

const int N = 60;
int n, m;
int g[N][N];
bool st[N][N];
int dirs[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};

void bfs(int i, int j) {
    queue<pair<int,int>> q;
    q.push(make_pair(i,j));
    st[i][j] = true;
    while (!q.empty()) {
        auto t = q.front();
        q.pop();
        for (int k = 0; k < 4; ++k) {
            int x = t.first + dirs[k][0];
            int y = t.second + dirs[k][1];
            if (x < 0 || x >= n || y < 0 || y >= m) continue;
            if (st[x][y]) continue;
            if (g[x][y] == 0) continue;
            q.push(make_pair(x,y));
            st[x][y] = true;
        }
    }
    return;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> g[i][j];
        }
    }
    
    memset(st, 0, sizeof st);
    int res = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (g[i][j] == 1 && st[i][j] == false) {
                bfs(i, j);
                res += 1;
            }
        }
    }
    cout << res << endl;
    
    return 0;
}

python3代码如下,

py 复制代码
#dfs写法
import collections 

s = input()
n, m = map(int, s.split())
g = [[0] * m for _ in range(n)]
st = [[False] * m for _ in range(n)]
for i in range(n):
    s = input()
    s = s.split()
    s = [int(x) for x in s]
    for j in range(len(s)):
        g[i][j] = s[j]

def dfs(i: int, j: int) -> None:
    global n, m, g 
    if i < 0 or i >= n or j < 0 or j >= m:
        return 
    if st[i][j]:
        return 
    if g[i][j] == 0:
        return 
    st[i][j] = True 
    dfs(i+1,j)
    dfs(i-1,j)
    dfs(i,j-1)
    dfs(i,j+1)
    return 
    
res = 0
for i in range(n):
    for j in range(m):
        if g[i][j] == 1 and st[i][j] == False:
            dfs(i,j)
            res += 1 
print(res)
py 复制代码
#bfs写法
import collections 

s = input()
n, m = map(int, s.split())
g = [[0] * m for _ in range(n)]
st = [[False] * m for _ in range(n)]
for i in range(n):
    s = input()
    ls = s.split()
    for j in range(len(ls)):
        x = int(ls[j])
        g[i][j] = x 

dirs = [[1,0],[-1,0],[0,1],[0,-1]]

def bfs(i: int, j: int) -> None:
    global n, m, g, st
    q = collections.deque([(i,j)])
    st[i][j] = True 
    while len(q) > 0:
        x, y = q.popleft()
        for k in range(4):
            nx = x + dirs[k][0]
            ny = y + dirs[k][1]
            if nx < 0 or nx >= n or ny < 0 or ny >= m:
                continue 
            if st[nx][ny]:
                continue 
            if g[nx][ny] == 0:
                continue 
            q.append((nx,ny))
            st[nx][ny] = True 
    return 

res = 0
for i in range(n):
    for j in range(m):
        if g[i][j] == 1 and st[i][j] == False:
            bfs(i,j)
            res += 1 
print(res)

题目3100. 岛屿的最大面积

解题思路:正常bfs和dfs即可。

C++代码如下,

cpp 复制代码
//dfs解法
#include <bits/stdc++.h>

using namespace std;

const int N = 60;
int n, m;
int g[N][N];
bool st[N][N];
int dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};

int dfs(int i, int j) {
    if (i < 0 || i >= n || j < 0 || j >= m) return 0;
    if (g[i][j] == 0) return 0;
    if (st[i][j] == true) return 0;
    
    int res = 1;
    st[i][j] = true;
    for (int k = 0; k < 4; ++k) {
        int ni = i + dirs[k][0];
        int nj = j + dirs[k][1];
        res += dfs(ni, nj);
    }
    return res;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> g[i][j];
        }
    }
    
    int res = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (g[i][j] == 1 && st[i][j] == false) {
                int ans = dfs(i, j);
                res = max(res, ans);
            }
        }
    }
    
    cout << res << endl;
    
    return 0;
}
cpp 复制代码
//bfs版本
#include <bits/stdc++.h>

using namespace std;

const int N = 60;
int n, m;
int g[N][N];
bool st[N][N];
int dirs[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};

int bfs(int i, int j) {
    queue<pair<int,int>> q;
    q.push(make_pair(i,j));
    st[i][j] = true;
    int ans = 1;

    while (!q.empty()) {
        auto t = q.front();
        q.pop();
        int i = t.first;
        int j = t.second;
        for (int k = 0; k < 4; ++k) {
            int ni = i + dirs[k][0];
            int nj = j + dirs[k][1];
            if (ni < 0 || ni >= n || nj < 0 || nj >= m) continue;
            if (g[ni][nj] == 0) continue;
            if (st[ni][nj]) continue;
            q.push(make_pair(ni,nj));
            st[ni][nj] = true;
            ans += 1;
        }
    }
    return ans;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> g[i][j];
        }
    }

    memset(st, 0, sizeof st);
    int res = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (g[i][j] == 1 && st[i][j] == false) {
                int ans = bfs(i, j);
                res = max(res, ans);
            }
        }
    }
    cout << res << endl;
    return 0;
}

python3代码如下,

py 复制代码
#dfs版本
import collections 

s = input()
n, m = map(int, s.split())
g = [[0] * m for _ in range(n)]
st = [[False] * m for _ in range(n)]
for i in range(n):
    s = input()
    s = s.split()
    for j in range(len(s)):
        x = int(s[j])
        g[i][j] = x 
res = 0
dirs = [[1,0], [-1,0], [0,-1], [0,1]]

def dfs(i: int, j: int) -> int:
    global n, m, g, st 
    if i < 0 or i >= n  or j < 0 or j >= m:
        return 0
    if g[i][j] == 0:
        return 0
    if st[i][j] == True:
        return 0
    res = 1 
    st[i][j] = True 
    for k in range(4):
        ni = i + dirs[k][0]
        nj = j + dirs[k][1]
        res += dfs(ni, nj)
    return res 
for i in range(n):
    for j in range(m):
        if g[i][j] == 1 and st[i][j] == False:
            ans = dfs(i,j)
            res = max(res, ans)
print(res)
py 复制代码
#bfs版本
import collections 

s = input()
n, m = map(int, s.split())
g = [[0] * m for _ in range(n)]
st = [[False] * m for _ in range(n)]
dirs = [[1,0], [-1,0], [0,1], [0,-1]]

for i in range(n):
    s = input()
    s = s.split()
    for j in range(len(s)):
        x = int(s[j])
        g[i][j] = x 

def bfs(i: int, j: int) -> int:
    q = collections.deque([(i,j)])
    st[i][j] = True 
    ans = 1 
    while len(q) > 0:
        i, j = q[0]
        q.popleft()
        for k in range(4):
            ni = i + dirs[k][0]
            nj = j + dirs[k][1]
            if ni < 0 or ni >= n or nj < 0 or nj >= m:
                continue 
            if g[ni][nj] == 0:
                continue 
            if st[ni][nj]:
                continue 
            q.append((ni,nj))
            st[ni][nj] = True 
            ans += 1 
    return ans 

res = 0
for i in range(n):
    for j in range(m):
        if g[i][j] == 1 and st[i][j] == False:
            ans = bfs(i,j)
            res = max(res, ans)
print(res)

题目4101. 孤岛的总面积

解题思路:

C++代码如下,

cpp 复制代码
//dfs版本
#include <bits/stdc++.h>

using namespace std;

const int N = 60;
int n, m;
int g[N][N];
int st[N][N];
int dirs[4][2] = {{1,0}, {-1,0}, {0,-1}, {0,1}};

int dfs(int i, int j) {
    if (i < 0 || i >= n || j < 0 || j >= m) return 0;
    if (st[i][j]) return 0;
    if (g[i][j] == 0) return 0;
    int ans = 1;
    st[i][j] = true;
    for (int k = 0; k < 4; ++k) {
        int ni = i + dirs[k][0];
        int nj = j + dirs[k][1];
        ans += dfs(ni,nj);
    }
    return ans;
}

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            cin >> g[i][j];
        }
    }
    
    memset(st, 0, sizeof st);
    
    for (int j = 0; j < m; ++j) {
        dfs(0,j);
        dfs(n-1,j);
    }
    for (int i = 0; i < n; ++i) {
        dfs(i,0);
        dfs(i,m-1);
    }
    
    int res = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (g[i][j] == 1 && st[i][j] == false) {
                res += dfs(i,j);
            }
        }
    }
    cout << res << endl;
    
    return 0;
}

python3代码如下,

py 复制代码

3 参考

代码随想录官网

相关推荐
chan_lay2 天前
图论导引 - 目录、引言、第一章 - 11/05
笔记·图论
£suPerpanda2 天前
牛客周赛 Round65 补题DEF
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
c沫栀3 天前
E-小H学历史(牛客练习赛131)
c++·算法·深度优先·图论
小冉在学习3 天前
day50 图论章节刷题Part02(99.岛屿数量 深搜、99.岛屿数量 广搜、100.岛屿的最大面积)
图论
weixin_478689763 天前
【图论】——理论基础总结
图论
夜雨翦春韭3 天前
【代码随想录Day60】图论Part11
java·数据结构·算法·leetcode·图论
夜雨翦春韭4 天前
【代码随想录Day52】图论Part04
java·数据结构·算法·leetcode·图论
X BoHang5 天前
10.31模拟赛题解
算法·图论
夜雨翦春韭5 天前
【代码随想录Day59】图论Part10
java·开发语言·数据结构·算法·leetcode·图论
deephub5 天前
基于图论的时间序列数据平稳性与连通性分析:利用图形、数学和 Python 揭示时间序列数据中的隐藏模式
人工智能·机器学习·图论·时间序列·1024程序员节