2차원 배열. 연결 안된 노드끼리는 비용이 무한. 모든 관계를 저장하므로 노드 개수 많으면 메모리 낭비됨. but 연결 여부 빨리 탐색 가능
linked list. 연결된 정보만 저장. 특정 노드와 연결된 모든 인접 노드를 순회해야 하는 경우 유리함.
시간복잡도 O(N)
시간복잡도 O(N)
최적해 보장. 주로 최단 거리 문제
2차원 배열 탐색 문제다? 그래프로 바꿔보자!
음료수 얼려먹기 - dfs
const ice = (n, m, map) => {
const board = map;
console.log(board);
const result = 0;
const dfs = (x, y) => {
if (x <= -1 || x >= n || y <= -1 || y >= m) {
return false;
}
if (board[x][y] === 0) {
board[x][y] === 1;
dfs(x - 1, y);
dfs(x + 1, y);
dfs(x, y - 1);
dfs(x, y + 1);
return true;
}
return false;
};
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (dfs(i, j) === true) {
result++;
}
}
}
return result;
};
const map = [
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
];
console.log(ice(4, 5, map));
미로찾기 - bfs
const solution = (n, m, board) => {
const queue = [];
//상하좌우
const dx = [-1, 1, 0, 0];
const dy = [0, 0, -1, 1];
const vfs = (x, y) => {
queue.push([x, y]);
while (queue.length) {
const now = queue.shift();
x = now[0];
y = now[1];
for (let i = 0; i < 4; i++) {
let newX = x + dx[i];
let newY = y + dy[i];
if (newX < 0 || newX >= n || newY < 0 || newY >= m) continue;
if (board[newX][newY] === 0) continue;
if (board[newX][newY] === 1) {
board[newX][newY] = board[x][y] + 1;
queue.push([newX, newY]);
}
}
}
return board[n - 1][m - 1];
};
return vfs(0, 0);
};
const map = [
[1, 0, 1, 0, 1, 0],
[1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
];
console.log(solution(5, 6, map));