[Algorithm/Java] SWEA 11315번 - 오목 판정
🔍 문제 풀이
문제 도식화
풀이 방법
연속된 칸을 검사하는 방법
// 기준 좌표에서 k칸 떨어진 위치를 계산하는 방식
for (int k = 0; k < 5; k++) {
int nx = x + dx[d] * k;
int ny = y + dy[d] * k;
...
}
💻 전체 코드
4방향 검사
import java.io.*;
public class Solution {
static int n;
static char[][] arr;
static int[] dx = {1, 1, 1, 0};
static int[] dy = {-1, 0, 1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= t; tc++) {
// 입력 및 초기화
n = Integer.parseInt(br.readLine());
arr = new char[n][n];
for (int i = 0; i < n; i++) {
String line = br.readLine();
for (int j = 0; j < n; j++) {
arr[i][j] = line.charAt(j);
}
}
boolean ans = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 'o' && solve(i, j)) {
ans = true;
break;
}
}
if (ans) break;
}
System.out.print("#" + tc + " ");
if(ans) System.out.println("YES");
else System.out.println("NO");
}
}
static boolean solve(int x, int y) {
for(int d=0; d<4; d++) {
int cnt = 0;
for (int z = 0; z < 5; z++) {
int nx = x + dx[d] * z;
int ny = y + dy[d] * z;
if (nx < 0 || nx >= n || ny < 0 || ny >= n) break;
if (arr[nx][ny] == 'o') cnt++;
}
if (cnt >= 5) return true;
}
return false;
}
}
시작점 단방향 검사 (초기 코드)
static boolean solve(int x, int y) {
// 열 검사
int cnt = 0;
for (int j = 0; j < n; j++) {
if (arr[x][j] == 'o') cnt++;
else cnt = 0;
if (cnt >= 5) return true;
}
// 행 검사
cnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i][y] == 'o') cnt++;
else cnt = 0;
if (cnt >= 5) return true;
}
// 대각선 \ 검사
cnt = 1;
int nx = x + 1, ny = y + 1;
while (nx < n && ny < n && arr[nx][ny] == 'o') {
cnt++;
nx++;
ny++;
}
if (cnt >= 5) return true;
// 대각선 / 검사
cnt = 1;
nx = x + 1;
ny = y - 1;
while (nx < n && ny >= 0 && arr[nx][ny] == 'o') {
cnt++;
nx++;
ny--;
}
if (cnt >= 5) return true;
return false;
}
스켈레톤 코드
import java.io.*;
public class Solution {
static int n;
static char[][] arr;
static int[] dx = {1, 1, 1, 0};
static int[] dy = {-1, 0, 1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= t; tc++) {
// 입력 및 초기화
n = Integer.parseInt(br.readLine());
arr = new char[n][n];
for (int i = 0; i < n; i++) {
String line = br.readLine();
for (int j = 0; j < n; j++) {
arr[i][j] = line.charAt(j);
}
}
boolean ans = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == 'o' && solve(i, j)) {
ans = true;
break;
}
}
if (ans) break;
}
System.out.print("#" + tc + " ");
if(ans) System.out.println("YES");
else System.out.println("NO");
}
}
static boolean solve(int x, int y) {
return false;
}
}
댓글남기기