Created
April 11, 2023 20:49
-
-
Save kangkyu/00d657f6fee5b0aa1c7e96bd21e246eb to your computer and use it in GitHub Desktop.
Leetcode answer (not working)
This file contains 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
type Cell struct { | |
north, east, south, west int | |
} | |
func numEnclaves(grid [][]int) int { | |
// return value of this func | |
count := 0 | |
// row count | |
m := len(grid) | |
// column count | |
n := len(grid[0]) | |
// To add up number of cells (1 or 0) | |
rowSum := make([]int, m) | |
colSum := make([]int, n) | |
cells := make([][]Cell, m) | |
for index := range cells { | |
cells[index] = make([]Cell, n) | |
} | |
for i := 0; i < m; i += 1 { | |
// same row i | |
for j := 0; j < n; j += 1 { | |
if grid[i][j] == 1 { | |
cells[i][j] = Cell{ | |
west: rowSum[i], | |
north: colSum[j], | |
} | |
} | |
// sum of i-th row numbers | |
rowSum[i] += grid[i][j] | |
// sum of j-th column numbers | |
colSum[j] += grid[i][j] | |
} | |
} | |
for i := 0; i < m; i += 1 { | |
for j := 0; j < n; j += 1 { | |
if grid[i][j] == 1 { | |
cells[i][j].east = rowSum[i] - cells[i][j].west - grid[i][j] | |
cells[i][j].south = colSum[j] - cells[i][j].north - grid[i][j] | |
if isIsland(cells[i][j], m, n, i, j) { | |
count += 1 | |
} | |
} | |
} | |
} | |
return count | |
} | |
func isIsland(cell Cell, m, n, i, j int) bool { | |
if i == 0 || i == m - 1 || j == 0 || j == n - 1 { | |
return false | |
} | |
return cell.north < i && cell.west < j && cell.south < m - i - 1 && cell.east < n - i - 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment