代码随想录 day52 第十一章 图论part03


title: 代码随想录 day52 第十一章 图论part03

date: 2024-12-23 01:35:07
modificationDate: 2024 十二月 23日 星期一 01:35:07
categories:

  • carl
    tags: []
    sticky: []
    hide: false
    category_bar: true

第十一章:图论part03

101. 孤岛的总面积

基础题目 可以自己尝试做一做 。

https://www.programmercarl.com/kamacoder/0101.孤岛的总面积.html

go 复制代码
package main

import (
    "fmt"
)

var count int
var dir = [4][2]int{{0, 1}, {1, 0}, {-1, 0}, {0, -1}} // 四个方向

func bfs(grid [][]int, x, y int) {
    queue := [][2]int{{x, y}}
    grid[x][y] = 0 // 只要加入队列,立刻标记
    count++
    
    for len(queue) > 0 {
        cur := queue[0]
        queue = queue[1:]
        curx, cury := cur[0], cur[1]
        
        for i := 0; i < 4; i++ {
            nextx := curx + dir[i][0]
            nexty := cury + dir[i][1]
            
            if nextx < 0 || nextx >= len(grid) || nexty < 0 || nexty >= len(grid[0]) {
                continue // 越界了,直接跳过
            }
            
            if grid[nextx][nexty] == 1 {
                queue = append(queue, [2]int{nextx, nexty})
                count++
                grid[nextx][nexty] = 0 // 只要加入队列立刻标记
            }
        }
    }
}

func main() {
    var n, m int
    fmt.Scan(&n, &m)
    
    grid := make([][]int, n)
    for i := range grid {
        grid[i] = make([]int, m)
    }
    
    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            fmt.Scan(&grid[i][j])
        }
    }
    
    // 从左侧边,和右侧边向中间遍历
    for i := 0; i < n; i++ {
        if grid[i][0] == 1 {
            bfs(grid, i, 0)
        }
        if grid[i][m-1] == 1 {
            bfs(grid, i, m-1)
        }
    }
    
    // 从上边和下边向中间遍历
    for j := 0; j < m; j++ {
        if grid[0][j] == 1 {
            bfs(grid, 0, j)
        }
        if grid[n-1][j] == 1 {
            bfs(grid, n-1, j)
        }
    }
    
    // 清空之前的计数
    count = 0
    
    // 遍历所有位置
    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            if grid[i][j] == 1 {
                bfs(grid, i, j)
            }
        }
    }
    
    fmt.Println(count)
}

102. 沉没孤岛

和上一题差不多,尝试自己做做

https://www.programmercarl.com/kamacoder/0102.沉没孤岛.html

103. 水流问题

需要点优化思路,建议先自己读题,相处一个解题方法,有时间就自己写代码,没时间就直接看题解,优化方式 会让你 耳目一新。

https://www.programmercarl.com/kamacoder/0103.水流问题.html

104.建造最大岛屿

同样优化思路也会让你耳目一新,自己想比较难想出来。

https://www.programmercarl.com/kamacoder/0104.建造最大岛屿.html

相关推荐
YSRM1 天前
Leetcode+Java+图论+岛屿问题
java·算法·leetcode·图论
失散133 天前
软件设计师——03 数据结构(下)
数据结构·软考·图论·软件设计师
YA10JUN4 天前
C++版搜索与图论算法
c++·算法·图论
蒙奇D索大5 天前
【数据结构】图论核心应用:关键路径算法详解——从AOE网到项目管理实战
数据结构·笔记·学习·考研·算法·图论·改行学it
钮钴禄·爱因斯晨6 天前
数据结构|图论:从数据结构到工程实践的核心引擎
c语言·数据结构·图论
heeheeai7 天前
kotlin图算法
算法·kotlin·图论
杨小码不BUG9 天前
CSP-J/S初赛知识点精讲-图论
c++·算法·图论··编码·csp-j/s初赛
(❁´◡`❁)Jimmy(❁´◡`❁)10 天前
【Trie】 UVA1401 Remember the Word
算法·word·图论
qq_4182478811 天前
论文阅读:TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
论文阅读·人工智能·深度学习·图论
希望201720 天前
图论基础知识
算法·图论