😎풀이

  1. 현재 구하고자 하는 값의 좌표를 탐색하는 getValueCoord 선언
    1-1. 값이 고유하므로, 2중 탐색을 통해 O(n) 시간 복잡도로 탐색
  2. 인접한 셀의 합계를 구하는 adjacentSum 정의
    2-1. 0 이상이며, grid를 벗어나지 않는 범위내에서 인접한 상하좌우 셀의 합계 반환
  3. 인접한 대각선의 합계를 구하는 diagonalSum 정의
    3-1. 0 이상이며, grid를 벗어나지 않는 범위내에서 인접한 좌상, 우상, 좌하, 우하 셀 합계 반환
class NeighborSum {
    private grid: number[][]
    private rowMax: number
    private colMax: number
    constructor(grid: number[][]) {
        this.grid = grid
        this.rowMax = grid.length
        this.colMax = grid[0].length
    }

    adjacentSum(value: number): number {
        let sum = 0
        const [y, x] = this.getValueCoord(value)
        if(y > 0) sum += this.grid[y - 1][x]
        if(x < this.colMax - 1) sum += this.grid[y][x + 1]
        if(y < this.rowMax - 1) sum += this.grid[y + 1][x]
        if(x > 0) sum += this.grid[y][x - 1]
        return sum
    }

    diagonalSum(value: number): number {
        let sum = 0
        const [y, x] = this.getValueCoord(value)
        if(y - 1 >= 0 && x - 1 >= 0) sum += this.grid[y - 1][x - 1]
        if(y - 1 >= 0 && x + 1 < this.colMax) sum += this.grid[y - 1][x + 1]
        if(y + 1 < this.rowMax && x - 1 >= 0) sum += this.grid[y + 1][x - 1]
        if(y + 1 < this.rowMax && x + 1 < this.colMax) sum += this.grid[y + 1][x + 1]
        return sum
    }

    getValueCoord(value: number) {
        let x: number
        let y: number
        for(let row = 0; row < this.grid.length; row++) {
            for(let col = 0; col < this.grid[0].length; col++) {
                if(this.grid[row][col] !== value) continue
                y = row
                x = col
            }
        }
        return [y, x]
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글