[프로그래머스] 혼자서 하는 틱택토 java

Bong2·2024년 4월 27일
0

알고리즘

목록 보기
5/63

문제 혼자서 하는 틱택토

문제 접근방법

  • 현재까지 한 게임의 결과가 규칙에 위반하는지 판단하여 단순히 규칙들을 구현하는 문제이다.

풀이

  • 규칙을 위반하는 경우
  1. 후공의 갯수가 선공보다 많은 경우
  2. 선공이 후공의 갯수보다 2번 더 많은 경우 ex) 선공 3, 후공 1
  3. 선공이 빙고된 경우에 선공과 후공의 갯수가 일치하는 경우
  4. 후공이 빙고된 경우에 선공을 더 한 경우
class Solution {
    public int solution(String[] board) {
        int answer = -1;
        
        //후공부터 시작한 경우
        int cnt[] = getFristLast(board);
        int first = cnt[0];
        int last = cnt[1];
        
        //안되는 경우
        //1. 후공의 갯수 선공보다 더 많은 경우
        if(first < last )
        {
            return 0;
        }
        
        //2. 선공이 후공보다 2번 더한경우 선공3 후공 1
        if(first > last+1)
        {
            return 0;
        }
        
        //3. 선공이 끝난 경우
        if(isFinishGame(board,'O') && first == last)
        {
            return 0;
        }
        
        //4. 후공이 끝난 경우
        if(isFinishGame(board,'X') && first > last)
        {
            return 0;
        }
        
        return 1;
    }
    
    //빙고가 된 경우
    public boolean isFinishGame(String []board , char c)
    {
        //가로 ㅡ
        for(int i = 0; i<3;i++)
        {
            if(board[i].charAt(0) == c && board[i].charAt(1) == c && board[i].charAt(2) == c)
            {
                return true;
            }
        }
        //세로 |
        for(int i = 0; i<3;i++)
        {
            if(board[0].charAt(i) == c && board[1].charAt(i) == c && board[2].charAt(i) == c)
            {
                return true;
            }
        }
        //대각선 /
        if(board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c )
            return true;
        //대각선 `
        if(board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c )
            return true;
        
        return false;
    }
    
    public int[] getFristLast(String []board)
    {
        int first = 0;
        int last = 0;
        
        for(int i = 0;i < board.length; i++)
        {
            for(int j =0;j<board[i].length();j++)
            {
                if('O' == board[i].charAt(j))
                {
                    first++;
                }else if('X' == board[i].charAt(j)){
                    last++;
                }
            }
        }
        
        return new int[]{first,last};
    }
}
profile
자바 백엔드 개발자로 성장하자

0개의 댓글