You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution {
enumclassDirection(valx:Int, valy:Int) {
Up(0, -1),
Down(0, 1),
Left(-1, 0),
Right(1, 0);
}
privatelateinitvar image:Array<IntArray>
privatevar color:Int=0privatevar starting:Int=0funisInside(dx:Int, dy:Int): Boolean {
return dx >=0&& dx < image.size && dy >=0&& dy < image[0].size
}
/* flood fill condition ( in order ) 1) current pos is inside 2) current pos is same as starting color 3) current pos is not yet colored*/funfloodFill(image:Array<IntArray>, sr:Int, sc:Int, color:Int): Array<IntArray> {
this.image = image
this.color = color
this.starting = image[sr][sc]
fillBFS(sr, sc)
// fillDFS(sr, sc)returnthis.image
}
// process dfs with recursivefunfillDFS(x:Int, y:Int) {
if (isInside(x, y) && image[x][y] == starting && image[x][y] != color) {
image[x][y] = color
for (di inDirection.values()) {
fillDFS(x + di.x, y + di.y)
}
}
}
// process bfs with processing queuefunfillBFS(sr:Int, sc:Int) {
val fillQ = mutableListOf<Pair<Int,Int>>(Pair(sr, sc))
while (!fillQ.isEmpty()) {
val c = fillQ.get(0)
fillQ.removeAt(0)
val x = c.first
val y = c.second
if (image[x][y] == color) continue
image[x][y] = color
for (di inDirection.values()) {
val dx = x + di.x
val dy = y + di.y
if (isInside(dx, dy) && image[dx][dy] == starting) fillQ.add(Pair(dx, dy))
}
}
}
}
695. Max Area of Island
langkotlin
tagsArrayDFSMatrix
classSolution {
enumclassDirection(valx:Int, valy:Int) {
Up(-1, 0),
Down(1, 0),
Left(0, -1),
Right(0, 1);
}
privatelateinitvar map:Array<IntArray>
privatevar group:Int=2funisInside(x:Int, y:Int): Boolean {
return x >=0&& x < map.size && y >=0&& y < map[0].size
}
funmaxAreaOfIsland(grid:Array<IntArray>): Int {
map = grid
var result =0// find partial-island from all map tilesfor (x in0..map.size-1) {
for (y in0..map[0].size-1) {
if (map[x][y] ==1) {
// count each groups' number of island// group will distinguish island if i already checkedval tmp = trackIsland(x, y)
result =Math.max(result, tmp)
group++
}
}
}
return result
}
funtrackIsland(x:Int, y:Int): Int {
// if is not inside or tile is (already checked or not island) count 0if (!isInside(x, y) || map[x][y] !=1) return0// coloring tile with group number and process 4-direction
map[x][y] = group
return1+
trackIsland(x +Direction.Up.x, y +Direction.Up.y) +
trackIsland(x +Direction.Down.x, y +Direction.Down.y) +
trackIsland(x +Direction.Left.x, y +Direction.Left.y) +
trackIsland(x +Direction.Right.x, y +Direction.Right.y)
}
}