[프로그래머스(Programmers)][Java,Python] (Lv1) 이웃한 칸 (PCCE 기출문제 9번)

728x90

 

https://school.programmers.co.kr/learn/courses/30/lessons/250125

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

1. Java

class Solution {
    public int solution(String[][] board, int h, int w) {
        int n = board.length;
        int count = 0;
        int[] dh = {0, 1, -1, 0}, dw = {1, 0, 0, -1};
        for ( int i = 0; i < 4; ++i ) {
            int h_next = h + dh[i];
            int w_next = w + dw[i];
            if ( h_next >= 0 && h_next < n &&
                 w_next >= 0 && w_next < n ) {
                if ( board[h][w].equals(board[h_next][w_next]) ) {
                    count++;
                }
            }
        }
        return count;
    }
}

 

2. Python

def solution(board, h, w):
    n = len(board)
    count = 0
    dh = [0, 1, -1, 0]
    dw = [1, 0, 0, -1]
    for i in range(4) :
        h_next = h + dh[i]
        w_next = w + dw[i]
        if h_next >= 0 and h_next < n and w_next >= 0 and w_next < n :
            if board[h][w] == board[h_next][w_next] :
                count += 1
    return count

 

반응형