xxxxxxxxxx
137
let walls = {};
let visited = {};
let q = [];
let val = 0;
let gridSize = 20;
const DFS = "DFS";
const BFS = "BFS";
let searchMode = BFS;
const WALL = "WALL";
const SRCH = "SRCH";
let drawMode = SRCH;
function setup() {
createCanvas(400, 400);
colorMode(HSB, 255);
}
function draw() {
background(220);
drawGrid();
if(q.length) {
let curr;
if(searchMode === DFS) {
curr = q.pop();
} else if(searchMode === BFS) {
curr = q.shift();
}
let pos = curr.split(":");
let x = parseInt(pos[0]) | 0;
let y = parseInt(pos[1]) | 0;
let n = neighbours(x, y);
for(let i = 0; i < n.length; i ++) {
if(!(n[i] in visited)) {
q.push(n[i]);
visited[n[i]] = val;
val = (val + 1) % 256;
}
}
}
fill(0);
text(searchMode, 10, 10);
text(drawMode, 10, 20);
}
function test() {
for(let i = 0; i < width; i ++) {
stroke(i % 256, 255, 255);
line(i, 0, i, height);
}
}
function neighbours(x, y) {
let n = [];
for(let i = -1; i <= 1; i ++) {
for(let j = -1; j <= 1; j ++) {
if(i === 0 && j === 0) {
continue;
}
let nx = (x + i) | 0;
let ny = (y + j) | 0;
let k = nx + ":" + ny;
if(inBounds(nx, ny) && !(k in walls)) {
n.push(k);
}
}
}
return n;
}
function inBounds(x, y) {
return x >= 0 && x < width/gridSize &&
y >= 0 && y < height/gridSize;
}
function keyTyped() {
if(key === "b") {
searchMode = BFS;
} else if(key === "d") {
searchMode = DFS;
} else if(key === "w") {
drawMode = WALL;
} else if(key === "s") {
drawMode = SRCH;
}
}
function mouseReleased() {
let x = (mouseX/gridSize) | 0;
let y = (mouseY/gridSize) | 0;
let k = x + ":" + y;
if(drawMode === SRCH) {
visited = {};
q = [k];
visited[k] = 0;
val = 1;
} else if(drawMode === WALL) {
if(k in walls) {
delete walls[k];
} else {
walls[k] = true;
}
}
}
function drawGrid() {
for(let j = 0; j < height/gridSize; j ++) {
for(let i = 0; i < width/gridSize; i ++) {
let k = i+":"+j;
if(k in walls) {
fill(0);
} else if(k in visited) {
fill(visited[k], 255, 255);
} else {
fill(0, 0, 255);
}
rect(i * gridSize, j * gridSize, gridSize, gridSize);
}
}
}