Algorithm/Programmers

[Programmers] 이웃한 칸 (Java)

Jyuni 2024. 1. 26. 17:46

문제 출처 : https://school.programmers.co.kr/learn/courses/30/lessons/250125

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 풀이

board[][]:색이 칠해진 보드판, h:x좌표, w:y좌표가 주어졌을 때, 인접한 4방향(상하좌우)과 동일한 색 개수 출력하기.
board[h][w] 좌표에서 4방향 탐색으로 dx, dy를 설정하고 범위 체크 후 같은 색이 있으면 answer++;

코드

class Solution {
    public int solution(String[][] board, int h, int w) {
        
        
        // init
        int answer = 0;
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        String color = board[h][w];
        
        // 4방향 탐색
        for(int dir=0; dir<4; dir++) {
            int nx = h + dx[dir];
            int ny = w + dy[dir];
            if(isRange(nx, ny, board.length) && color.equals(board[nx][ny])) answer++;
        }
        
        return answer;
    }
    
    public boolean isRange(int x, int y, int len) {
        return x>=0 && y>=0 && x<len && y<len;
    }
}