Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[BOJ 2615] 오목 (JAVA) 본문

Problem Solving

[BOJ 2615] 오목 (JAVA)

흑개 2022. 1. 24. 13:25

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

 

2615번: 오목

오목은 바둑판에 검은 바둑알과 흰 바둑알을 교대로 놓아서 겨루는 게임이다. 바둑판에는 19개의 가로줄과 19개의 세로줄이 그려져 있는데 가로줄은 위에서부터 아래로 1번, 2번, ... ,19번의 번호

www.acmicpc.net

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
	static int[] dr= {-1,1,0,0,-1,1,-1,1};
	static int[] dc= {0,0,-1,1,1,-1,-1,1};
	static int winner=0;
	static int ans_r=-1;
	static int ans_c=-1;
	public static void main(String[] args) throws FileNotFoundException {
		//System.setIn(new FileInputStream("Test5.txt"));
		Scanner sc=new Scanner(System.in);
		boolean isAnswer=false;
		int[][] board=new int[21][21];	//padding
		for (int i=1; i<=19; i++) {
			for (int j=1; j<=19; j++) {
				board[i][j]=sc.nextInt();
			}
		}
		for (int r=1; r<=19; r++) {
			for (int c=1; c<=19; c++) {
				if (board[r][c]!=0) {
					for (int k=0; k<8; k++) {		
						if (board[r-dr[k]][c-dc[k]]==board[r][c])
							continue;
						int cnt=1;
						int nr=r+dr[k];
						int nc=c+dc[k];
						while (true) {
							if (board[nr][nc]!=board[r][c]) {
								break;
							}
							cnt++;
							nr+=dr[k];
							nc+=dc[k];
						}
						if (cnt==5) {
								winner=board[r][c];
								saveAnswer(r,c,nr,nc,k);
								isAnswer=true;
								break;
						}
					}
				}
				if (isAnswer) {
					break;
				}
			}
			if (isAnswer)
				break;
		}
		System.out.println(winner);
		if (winner!=0) {
			System.out.printf("%d %d\n",ans_r, ans_c);
		}
	}
	public static void saveAnswer(int r, int c, int nr, int nc, int k) {
		nr-=dr[k];
		nc-=dc[k];
		switch(k) { 
		case 0: case 2: case 5: case 6:
			ans_r=nr;
			ans_c=nc;
			break;
		case 1: case 3: case 4: case 7:
			ans_r=r;
			ans_c=c;
			break;
		}
	}
}

padding을 이용해 경계체크를 할 필요가 없게 만든다.

여기서 중요한 건 탐색할 때 자기 앞에 있는 것(r-dr[i], c-dc[i])이 자기의 값과 같지 않은 경우만 탐색해야 된다는 것이다.