Created
June 12, 2022 03:06
-
-
Save sychonet/228a4ac4c5b0553c2d00186b4389b7b8 to your computer and use it in GitHub Desktop.
A solution for problem walls and gates on leetcode in Solang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A solution for walls and gates problem on leetcode in golang | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
const EMPTY int = math.MaxInt32 | |
const GATE int = 0 | |
const WALL int = -1 | |
var DIRECTIONS = [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} | |
type queue struct { | |
data [][]int | |
head int | |
} | |
func (q *queue) enqueue(node []int) { | |
q.data = append(q.data, node) | |
} | |
func (q *queue) dequeue() []int { | |
val := q.data[q.head] | |
q.head++ | |
return val | |
} | |
func (q *queue) isEmpty() bool { | |
if q.head == len(q.data) { | |
return true | |
} | |
return false | |
} | |
func wallsAndGates(rooms [][]int) { | |
if len(rooms) == 0 { | |
return | |
} | |
for row := 0; row < len(rooms); row++ { | |
for col := 0; col < len(rooms[0]); col++ { | |
if rooms[row][col] == EMPTY { | |
rooms[row][col] = distanceToNearestGate(rooms, row, col) | |
} | |
} | |
} | |
} | |
func distanceToNearestGate(rooms [][]int, startRow int, startCol int) int { | |
m := len(rooms) | |
n := len(rooms[0]) | |
var distance [][]int | |
distance = make([][]int, m) | |
for i := 0; i < m; i++ { | |
distance[i] = make([]int, n) | |
} | |
var q queue | |
var node = []int{startRow, startCol} | |
q.enqueue(node) | |
for !q.isEmpty() { | |
point := q.dequeue() | |
row := point[0] | |
col := point[1] | |
for _, direction := range DIRECTIONS { | |
r := row + direction[0] | |
c := col + direction[1] | |
if r < 0 || c < 0 || r >= m || c >= n || rooms[r][c] == WALL || distance[r][c] != 0 { | |
continue | |
} | |
distance[r][c] = distance[row][col] + 1 | |
if rooms[r][c] == GATE { | |
return distance[r][c] | |
} | |
var newNode = []int{r, c} | |
q.enqueue(newNode) | |
} | |
} | |
return math.MaxInt32 | |
} | |
func main() { | |
var rooms = [][]int{{2147483647, -1, 0, 2147483647}, {2147483647, 2147483647, 2147483647, -1}, {2147483647, -1, 2147483647, -1}, {0, -1, 2147483647, 2147483647}} | |
wallsAndGates(rooms) | |
fmt.Println(rooms) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try this on https://go.dev/play/p/k17qkxo6YVH