Skip to content

Instantly share code, notes, and snippets.

@getify
Last active February 14, 2023 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/3df743ca0fd80a2ea1b630dccb62c820 to your computer and use it in GitHub Desktop.
Save getify/3df743ca0fd80a2ea1b630dccb62c820 to your computer and use it in GitHub Desktop.
// 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