Skip to content

Instantly share code, notes, and snippets.

@baeharam
Created October 31, 2019 12:52
Show Gist options
  • Save baeharam/7a058e399191941d771b490c57d77886 to your computer and use it in GitHub Desktop.
Save baeharam/7a058e399191941d771b490c57d77886 to your computer and use it in GitHub Desktop.
BFS implementation
const paintAdjcent = (x, y, tableData) => {
const queue = [];
const row = tableData.length, col = tableData[0].length;
const visited = new Array(row).fill();
visited.forEach((_, idx) => { visited[idx] = new Array(col).fill(false); });
visited[x][y] = true;
queue.push({x: x,y: y});
while(typeof queue !== 'undefined' && queue.length > 0) {
const front = queue.shift();
tableData[front.x][front.y] = CODE.OPENED;
let count = 0;
for(let i=0; i<8; i++) {
const nextX = front.x + dx[i], nextY = front.y + dy[i];
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col) continue;
if (tableData[nextX][nextY] === CODE.MINE) count++;
}
if(count > 0) {
tableData[front.x][front.y] = count;
continue;
}
count = 0;
for(let i=0; i<8; i++) {
const nextX = front.x + dx[i], nextY = front.y + dy[i];
if (nextX < 0 || nextX >= row || nextY < 0 || nextY >= col) continue;
if (tableData[nextX][nextY] === CODE.MINE) {
count++;
continue;
}
if (visited[nextX][nextY]) continue;
if ([CODE.MINE, CODE.OPENED, CODE.FLAG, CODE.FLAG_MINE, CODE.QUESTION, CODE.QUESTION_MINE]
.includes(tableData[nextX][nextY])) {
continue;
}
queue.push({x: nextX, y: nextY});
visited[nextX][nextY] = true;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment