[백준 17265] 나의 인생에는 수학과 함께 with node.js

waterglasses·2021년 12월 26일
0

📌 문제

https://www.acmicpc.net/problem/17265

📌 풀이

  • 최단거리로 이동하기 위해 오른쪽, 아래쪽으로만 이동해야하기 때문에 dx, dy를 설정하고 이동하면서 숫자인지 문자인지 판별한다.
  • 숫자가 나오면 calcByOperation로 계산하여 DFS로 N-1, N-1이 나오면 최소값, 최대값을 갱신하였다.
  • node.js로 문제를 풀이하였지만 계속 틀렸습니다가 나왔지만 python으로는 성공하엿다.

📌 코드

  • node.js
// 문제 실패 : 반례가 떠오르지 않음
// 같은 로직으로 python으로 제출했을 시 정답처리가 되었다
const fs = require('fs');
const stdin = (
  process.platform === 'linux'
    ? fs.readFileSync('/dev/stdin').toString().trim()
    : `3
0 - 1
- 1 -
1 - 1`
).split('\n');

const input = (() => {
  let line = 0;
  return () => stdin[line++];
})();

const calcByOperation = (preVal, curVal, op) => {
  let result = 0;
  if (op === '+') {
    result = preVal + curVal;
  } else if (op === '-') {
    result = preVal - curVal;
  } else if (op === '*') {
    result = preVal * curVal;
  }
  return result;
};

const setMinMaxValueInMap = (x, y, curResult, operation) => {
  if (x === N - 1 && y === N - 1) {
    maxOfCalculation = Math.max(maxOfCalculation, curResult);
    minOfCalculation = Math.min(minOfCalculation, curResult);
    return;
  }

  for (let i = 0; i < 2; i++) {
    let nx = x + dx[i];
    let ny = y + dy[i];

    if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;

    let isNumber = !isNaN(map[nx][ny]);
    if (isNumber) {
      let calculationResult = calcByOperation(curResult, parseInt(map[nx][ny]), operation);
      setMinMaxValueInMap(nx, ny, calculationResult, operation);
    } else {
      setMinMaxValueInMap(nx, ny, curResult, map[nx][ny]);
    }
  }
};

const N = parseInt(input());
const map = Array.from(Array(N), () => input().split(' '));
let [maxOfCalculation, minOfCalculation] = [-Number.MAX_VALUE, Number.MAX_VALUE];
let dx = [1, 0];
let dy = [0, 1];

setMinMaxValueInMap(0, 0, parseInt(map[0][0]), '');
console.log(maxOfCalculation, minOfCalculation);
  • python
import sys
input = sys.stdin.readline

def calcByOperation(preVal, curVal, op):
    result = 0
    if op == '+':
        result = preVal + curVal
    if op == '-':
        result = preVal - curVal
    if op == '*':
        result = preVal * curVal
    return result

def setMinMaxValueInMap(x, y, curResult, operation):
    global maxOfCalculation, minOfCalculation ## 오...
    if x == N - 1 and y == N - 1:
        maxOfCalculation = max(maxOfCalculation, curResult)
        minOfCalculation = min(minOfCalculation, curResult)
        return

    for i in range(2):
        nx = x + dx[i]
        ny = y + dy[i]
        
        if nx < 0 or nx >= N or ny < 0 or ny >= N:
            continue
        
        if map[nx][ny].isdigit():
            calculationResult = calcByOperation(curResult, int(map[nx][ny]), operation)
            setMinMaxValueInMap(nx, ny, calculationResult, operation)
        else:
            setMinMaxValueInMap(nx, ny, curResult, map[nx][ny])


N = int(input())
map = list(input().split() for _ in range(N)) ## 욜..

dx, dy = [1, 0] , [0, 1]
maxOfCalculation, minOfCalculation = -(5 ** 20), 5 ** 20

setMinMaxValueInMap(0, 0, int(map[0][0]), '')
print(maxOfCalculation, minOfCalculation)
profile
매 순간 성장하는 개발자가 되려고 노력하고 있습니다.

0개의 댓글