js로 queue 구현
class MyQueue {
constructor() {
this.input = [];
this.output = [];
this.size = 0;
}
enque(val) {
this.input.push(val);
this.size++;
}
deque() {
if(this.output.length === 0) {
this.output = this.input.reverse();
this.input = [];
}
this.size--;
return this.output.pop();
}
}
const dr = [-1, 1, 0, 0];
const dc = [0, 0, -1, 1];
const R = maps.length;
const C = maps[0].length;
const visit = Array(R).fill(null).map(() => Array(C).fill(false));
const que = new MyQueue();
플로이드 와샬
function solution (n, s, a, b, fares) {
const board = new Array(n).fill().map(_ => new Array(n).fill(Infinity));
for(let i = 0; i < n; i++)
board[i][i] = 0;
fares.forEach(pos => {
const [x, y, weight] = pos;
board[x-1][y-1] = weight;
board[y-1][x-1] = weight;
});
// k는 경유노드, i는 시작노드, j는 도착노드
for(let k = 0; k < n; k++) {
for(let i = 0; i < n; i++) {
for(let j = 0; j < n; j++) {
if(board[i][j] > board[i][k] + board[k][j])
board[i][j] = board[i][k] + board[k][j];
}
}
}
let answer = board[s-1][a-1] + board[s-1][b-1];
for(let i = 0; i < n; i++) {
const shortest = board[s-1][i] + board[i][a-1] + board[i][b-1];
answer = Math.min(answer, shortest);
}
return answer;
}
union find
function solution(n, computers) {
const getParent = (arr, x) => {
if(arr[x] === x) return x;
return arr[x] = getParent(arr, arr[x]);
}
const unionParent = (arr, a, b) => {
a = getParent(arr, a);
b = getParent(arr, b);
if(a < b) {
arr[b] = a;
}
else if (a === b) {
return;
}
else {
arr[a] = b;
}
}
let answer = 0;
let parent = Array(n).fill(false);
for(let i = 0; i < n; i++){
parent[i] = i;
}
for(let i = 0; i < n; i++){
for(let j = 0; j < n; j++){
if(i === j){
continue;
}
if(computers[i][j]){
unionParent(parent, i, j);
}
}
}
for(let i = 0; i < n; i++){
if(parent[i] === i){
answer++;
}
}
return answer;
}
배열의 특정 값 삭제
const food = ["pizza", "mango", "kimchi", "kimbab"];
const target = 1;
const answer = [...food.slice(0, target) , ...food.slice(target+1);