Last active
February 14, 2023 03:11
-
-
Save getify/3df743ca0fd80a2ea1b630dccb62c820 to your computer and use it in GitHub Desktop.
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
// this is an experimental Foi (https://github.com/getify/foi-lang) implementation of | |
// the BFS solution to https://gist.github.com/getify/59ab7443723564eb40d20ab7c45d5f0a | |
def < :size, :log >: import "#Std"; | |
def M1: < | |
< 0, 0, 1, 1, 0 >, | |
< 1, 0, 1, 1, 0 >, | |
< 0, 1, 0, 0, 0 >, | |
< 0, 0, 0, 1, 1 > | |
>; | |
M1 #> findMaxRegionArea #> log; | |
// 6 | |
// ************************************ | |
// breadth-first iteration | |
defn findMaxRegionArea(matr) { | |
def ROW_LEN: size(matr.0); | |
def area: 0; | |
def maxArea: 0; | |
def visited: <>; | |
matr ~each (row,rowIdx) { | |
row ~each (cell,colIdx,cellCoords: <rowIdx,colIdx>) { | |
// found the edge of an area? | |
?[cell ?= 1 ?and visited !has cellCoords]: (toVisit: < cellCoords >) { | |
// exhaustively explore the rest of the area | |
?[size(toVisit) ?> 0] ~each ( | |
visitedRowIdx: toVisit.0.0, | |
visitedColIdx: toVisit.0.1 | |
) { | |
toVisit := toVisit.[1..]; // drop head, re-assign to tail | |
visited := visited $+ < cellCoords >; // $+ is set-append here | |
area := area + 1; | |
// explore the 8 surrounding cells | |
<-1,0,1> ~each (rowDelta) { | |
<-1,0,1> ~each (colDelta) { | |
// avoid re-considering the current cell | |
![rowDelta ?= 0 ?and colDelta ?= 0]: ( | |
toVisitRowIdx: visitedRowIdx + rowDelta, | |
toVisitColIdx: visitedColIdx + colDelta, | |
toVisitCoords: <toVisitRowIdx,toVisitColIdx> | |
) { | |
// is this candidate a valid cell we should visit? | |
?[(?and)( | |
(?<=>)(0, toVisitRowIdx, (matr.length - 1)), | |
(?<=>)(0, toVisitColIdx, (ROW_LEN - 1)), | |
matr[toVisitRowIdx][toVisitColIdx] ?= 1, | |
visited !has toVisitCoords, | |
toVisit !has toVisitCoords // since it's a set, not technically needed | |
)]: { | |
// add the cell to our `toVisit` queue (set) | |
toVisit := toVisit $+ < toVisitCoords > // $+ is set-append here | |
} | |
} | |
} | |
} | |
}; | |
maxArea := max(maxArea,area); | |
area := 0 | |
} | |
} | |
}; | |
^maxArea | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment