-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
function solution(numbers, target) {
let answer = 0;
dfs(0, 0);
function dfs(index, sum) {
if (index === numbers.length) {
if (sum === target) {
answer++;
}
return;
}
dfs(index + 1, sum + numbers[index]);
dfs(index + 1, sum - numbers[index]);
}
return answer;
}
There is a bi-directional graph with n
vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges
, where each edges[i] = [ui, vi]
denotes a bi-directional edge between vertex ui
and vertex vi
. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source
to vertex destination
.
Given edges
and the integers n
, source
, and destination
, return true
if there is a valid path from source to destination, or false
otherwise.
Example 1
Example 2
/**
* @param {number} n
* @param {number[][]} edges
* @param {number} source
* @param {number} destination
* @return {boolean}
*/
var validPath = function(n, edges, source, destination) {
let adjacencyList = {}, visited = {};
edges.forEach(([vertex1, vertex2]) => {
if (!adjacencyList[vertex1]) adjacencyList[vertex1] = [];
if (!adjacencyList[vertex2]) adjacencyList[vertex2] = [];
adjacencyList[vertex1].push(vertex2);
adjacencyList[vertex2].push(vertex1);
});
let stack = [source];
visited[source] = true;
while (stack.length) {
const current = stack.pop();
if (current === destination) return true;
for (let neighbor of adjacencyList[current]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
}
}
}
return false;
};
root
of a binary tree, return the sum of values of its deepest leaves.var deepestLeavesSum = function(root) {
let queue = [root];
let lastLevel = [];
while(queue.length) {
let size = queue.length;
let level = [];
for (let i = 0; i < size; i++) {
const node = queue.shift();
level.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
lastLevel = level;
}
return lastLevel.reduce((sum, val) => sum += val, 0);
};
[ 1 ]
[ 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8 ] // lastLevel
root
of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0./**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumEvenGrandparent = function(root) {
let result = 0;
traverse(root);
function traverse(node){
if (!node) return 0;
if (node.val % 2 === 0) {
if (node.left && node.left.left) {
result += node.left.left.val;
}
if (node.left && node.left.right) {
result += node.left.right.val;
}
if (node.right && node.right.left) {
result += node.right.left.val;
}
if (node.right && node.right.right) {
result += node.right.right.val;
}
}
traverse(node.left);
traverse(node.right);
}
return result;
};
function solution(n, computers) {
var answer = 0;
const length = computers.length;
let visited = new Array(length).fill(false);
function dfs(index) {
visited[index] = true;
for (let i = 0; i < n; i++) {
if (computers[index][i] === 1 && !visited[i]) {
dfs(i);
}
}
}
for (let index = 0; index < n; index++) {
if (!visited[index]) {
dfs(index);
answer++;
}
}
return answer;
}
n
nodes labeled from 0
to n - 1
, find all possible paths from node 0
to node n - 1
and return them in any order.graph[i]
is a list of all nodes you can visit from node i
(i.e., there is a directed edge from node i
to node graph[i][j]
)./**
* @param {number[][]} graph
* @return {number[][]}
*/
var allPathsSourceTarget = function(graph) {
const result = [];
const findPath = function(path, node) {
if (node === graph.length - 1) {
result.push([...path, node]);
return;
}
graph[node].forEach((neighbor) => findPath([...path, node], neighbor));
}
findPath([], 0);
return result;
};
function solution(n, edge) {
let answer = 0;
let node = Array.from({length: n+1}, () => []);
let visited = new Array(n+1).fill(0);
let queue = [1];
edge.forEach(([start, end]) => {
node[start].push(end);
node[end].push(start);
});
visited[1] = 1;
while(queue.length) {
let current = queue.shift();
node[current].forEach((neighbor) => {
if (!visited[neighbor]) {
queue.push(neighbor);
visited[neighbor] = visited[current] + 1;
}
});
}
const max = Math.max(...visited);
answer = visited.filter(edgeCount => edgeCount === max).length;
return answer;
}
n
cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.n
x n
matrix isConnected
where isConnected[i][j] = 1
if the ith city and the jth
city are directly connected, and isConnected[i][j] = 0
otherwise./**
* @param {number[][]} isConnected
* @return {number}
*/
var findCircleNum = function(isConnected) {
const visited = {};
let provinceCount = 0;
for (let cityIndex = 0; cityIndex < isConnected.length; cityIndex++){
if (!visited[cityIndex]) {
dfs(cityIndex);
provinceCount++;
}
}
function dfs(cityIndex) {
visited[cityIndex] = true;
for (let neighborIndex = 0; neighborIndex < isConnected[cityIndex].length; neighborIndex++) {
if (!visited[neighborIndex] && isConnected[cityIndex][neighborIndex] === 1) {
dfs(neighborIndex);
}
}
}
return provinceCount;
};
n
rooms labeled from 0
to n - 1
and all the rooms are locked except for room 0
. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.rooms
where rooms[i]
is the set of keys that you can obtain if you visited room i
, return true
if you can visit all the rooms, or false
otherwise./**
* @param {number[][]} rooms
* @return {boolean}
*/
var canVisitAllRooms = function(rooms) {
const visited = {};
dfs(0);
function dfs(i) {
visited[i] = true;
rooms[i].forEach((key) => {
if (!visited[key]) {
dfs(key);
}
});
}
for (let i = 0; i < rooms.length; i++) {
if (!visited[i]) {
return false;
}
}
return true;
};
n
vertices numbered from 0
to n-1
, and an array edges where edges[i] = [fromi, toi]
represents a directed edge from node fromi
to node toi
./**
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var findSmallestSetOfVertices = function(n, edges) {
const visited = new Array(n).fill(0);
const result = [];
edges.forEach(([start, end]) => visited[end]++);
visited.forEach((visitedCount, index) => {
if (!visitedCount) {
result.push(index);
}
});
return result;
};
begin
, target
과 단어의 집합 words
가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.function solution(begin, target, words) {
let answer = 0;
const hasTarget = words.includes(target);
if (!hasTarget) return 0;
function checkSimilarity(word1, word2) {
let differentLength = 0;
for (let i = 0; i < word1.length; i++) {
if (word1[i] !== word2[i]) {
differentLength++;
}
}
return differentLength === 1;
}
const visited = { [begin] : 0 };
const queue = [begin];
while (queue.length) {
const currWord = queue.shift();
if (currWord === target) break;
words.forEach((word) => {
if (!visited[word] && checkSimilarity(word, currWord)) {
visited[word] = visited[currWord] + 1;
queue.push(word);
}
});
}
return visited[target];
}
There are n computers numbered from 0
to n - 1
connected by ethernet cables connections
forming a network where connections[i] = [ai, bi]
represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network connections
. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1
.
Example 1:
/**
* @param {number} n
* @param {number[][]} connections
* @return {number}
*/
var makeConnected = function(n, connections) {
if (connections.length < n - 1) return -1;
let answer = 0;
const graph = Array.from({length: n}, () => []);
const visited = Array(n).fill(false);
connections.forEach(([start, end]) => {
graph[start].push(end);
graph[end].push(start);
});
const dfs = function(node) {
visited[node] = true;
graph[node].forEach((neighbor) => {
if (!visited[neighbor]) {
dfs(neighbor);
}
});
}
for (let index = 0; index < n; index++) {
if (!visited[index]) {
dfs(index);
answer++;
}
}
return answer - 1;
};
ROR 게임은 두 팀으로 나누어서 진행하며, 상대 팀 진영을 먼저 파괴하면 이기는 게임입니다. 따라서, 각 팀은 상대 팀 진영에 최대한 빨리 도착하는 것이 유리합니다.
지금부터 당신은 한 팀의 팀원이 되어 게임을 진행하려고 합니다. 다음은 5 x 5 크기의 맵에, 당신의 캐릭터가 (행: 1, 열: 1) 위치에 있고, 상대 팀 진영은 (행: 5, 열: 5) 위치에 있는 경우의 예시입니다.
위 그림에서 검은색 부분은 벽으로 막혀있어 갈 수 없는 길이며, 흰색 부분은 갈 수 있는 길입니다. 캐릭터가 움직일 때는 동, 서, 남, 북 방향으로 한 칸씩 이동하며, 게임 맵을 벗어난 길은 갈 수 없습니다.
아래 예시는 캐릭터가 상대 팀 진영으로 가는 두 가지 방법을 나타내고 있습니다.
첫 번째 방법은 11개의 칸을 지나서 상대 팀 진영에 도착했습니다.
위 예시에서는 첫 번째 방법보다 더 빠르게 상대팀 진영에 도착하는 방법은 없으므로, 이 방법이 상대 팀 진영으로 가는 가장 빠른 방법입니다.
만약, 상대 팀이 자신의 팀 진영 주위에 벽을 세워두었다면 상대 팀 진영에 도착하지 못할 수도 있습니다. 예를 들어, 다음과 같은 경우에 당신의 캐릭터는 상대 팀 진영에 도착할 수 없습니다.
게임 맵의 상태 maps
가 매개변수로 주어질 때, 캐릭터가 상대 팀 진영에 도착하기 위해서 지나가야 하는 칸의 개수의 최솟값을 return 하도록 solution 함수를 완성해주세요. 단, 상대 팀 진영에 도착할 수 없을 때는 -1
을 return 해주세요.
제한사항
function solution(maps) {
let answer = -1;
const n = maps.length;
const m = maps[0].length;
const dx = [-1, 0, 1, 0];
const dy = [0, 1, 0, -1];
const isOutBoundary = (x, y) => {
return x < 0 || x >= n || y < 0 || y >= m;
}
const bfs = () => {
const queue = [[0, 0, 1]];
maps[0][0] = 0;
while(queue.length) {
const [x, y, count] = queue.shift();
if (x === n - 1 && y === m - 1) {
answer = count;
break;
}
for (let i = 0; i < dx.length; i++) {
let nx1 = x + dx[i];
let ny1 = y + dy[i];
if (isOutBoundary(nx1, ny1)) {
continue;
}
if (maps[nx1][ny1] === 1) {
maps[nx1][ny1] = 0;
queue.push([nx1, ny1, count + 1]);
}
}
}
}
bfs();
return answer;
}
주어진 항공권을 모두 이용하여 여행경로를 짜려고 합니다. 항상 "ICN" 공항에서 출발합니다.
항공권 정보가 담긴 2차원 배열 tickets
가 매개변수로 주어질 때, 방문하는 공항 경로를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한사항
tickets
의 각 행 [a, b]는 a 공항에서 b 공항으로 가는 항공권이 있다는 의미입니다.입출력 예
function solution(tickets) {
const totalTicketCount = tickets.length;
const visited = new Array(totalTicketCount).fill(false);
let answer;
tickets.sort();
const dfs = (airport, airportCount, path) => {
console.log(path);
if (airportCount === totalTicketCount && !answer) {
answer = path;
return;
}
for (let ticketIndex = 0; ticketIndex < totalTicketCount; ticketIndex++) {
if (visited[ticketIndex]) {
continue;
}
let [startAirport, endAirport] = tickets[ticketIndex];
if (airport === startAirport) {
visited[ticketIndex] = true;
dfs(endAirport, airportCount + 1, [...path, endAirport]);
visited[ticketIndex] = false;
}
}
}
dfs('ICN', 0, ['ICN']);
return answer;
}
Given an m x n
matrix board where each cell is a battleship 'X'
or empty '.'
, return the number of the battleships on board.
Battleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k
(1
row, k
columns) or k x 1
(k
rows, 1
column), where k
can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
Example 1:
/**
* @param {character[][]} board
* @return {number}
*/
var countBattleships = function(board) {
const m = board.length;
const n = board[0].length;
const visited = Array.from({length: m}, () => new Array(n).fill(false));
let battleshipsCount = 0;
const dfs = (row, col) => {
visited[row][col] = true;
if ( col + 1 < n && board[row][col+1] === 'X') {
for (let nextCol = col + 1; nextCol < n; nextCol++) {
if (board[row][nextCol] === 'X') {
visited[row][nextCol] = true;
continue;
}
if (board[row][nextCol] === '.') {
return;
}
}
}
if ( row + 1 < m && board[row+1][col]=== 'X') {
for (let nextRow = row + 1; nextRow < m; nextRow++) {
if (board[nextRow][col] === 'X') {
visited[nextRow][col] = true;
continue;
}
if (board[nextRow][col] === '.') {
return;
}
}
}
}
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
if (!visited[row][col] && board[row][col] === 'X') {
dfs(row, col);
battleshipsCount++;
}
}
}
return battleshipsCount;
};
storey
가 주어졌을 때, 0층으로 가기 위해 필요한 마법의 돌의 최소값을 return 하도록 solution 함수를 완성하세요.storey
≤ 100,000,000function solution(storey) {
let answer = 100000000;
const dfs = (num, movement) => {
if (movement >= answer) {
return;
}
if (num === 0) {
answer = movement;
return;
}
const digit = num % 10;
// 층을 내려갔을 경우
dfs(Math.floor(num/10), movement + digit);
// 층을 올라갔을 경우
dfs(Math.floor(num/10) + 1, movement + 10 - digit);
};
dfs(storey, 0);
return answer;
}