Skip to content

Instantly share code, notes, and snippets.

@pot-code
Last active April 6, 2020 04:05
Show Gist options
  • Save pot-code/a1619d0ed7b5df9b5d248e5f4343f033 to your computer and use it in GitHub Desktop.
Save pot-code/a1619d0ed7b5df9b5d248e5f4343f033 to your computer and use it in GitHub Desktop.
[BFS] breadth first search #algorithm
var directions = [4][2]int{{0, 1}, {0, -1}, {-1, 0}, {1, 0}}
func bfs(grid [][]int) {
var (
queue [][]int
m = len(grid)
n = len(grid[0])
)
for len(queue) > 0 {
for size := len(queue); size > 0; size-- {
point := queue[0]
queue = queue[1:]
for _, dir := range directions {
nr, nc := point[0]+dir[0], point[1]+dir[1]
if nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == 0 {
grid[nr][nc] = 1
queue = append(queue, []int{nr, nc})
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment