1. 코드
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Comparator;
class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; i++) {
// 1. 퍼즐 구조 2차원 배열로 받기.
int N = sc.nextInt();
int K = sc.nextInt();
int [][] puzzle = new int[N][N];
ArrayList<Integer> container = new ArrayList<>();
for (int j = 0; j < N; j++) {
for (int k = 0; k < N; k++) {
puzzle[j][k] = sc.nextInt();
}
}
// 2. 밑의 과정을 반복한다.
// 2-1. 행마다 연속된 1의 값을 ArrayList에 집어넣는다.
// 가로만 봤을 때 퍼즐을 넣을 수 있는 공간 체크하기
for (int j = 0; j < N; j++) {
int temp = 0;
for (int k = 0; k < N; k++) {
if(puzzle[j][k] == 1){
temp +=1;
}else if(puzzle[j][k] == 0) {
if(temp == 0) {continue;}
container.add(temp);
temp = 0;
}
if(k == N-1) {
if(temp== 0){continue;}
container.add(temp);
}
}
}
// 세로만 봤을 때 퍼즐 들어갈 수 있는 공간 체크
for (int j = 0; j < N; j++) {
int temp = 0;
for (int k = 0; k < N; k++) {
if(puzzle[k][j] == 1){
temp +=1;
}else if(puzzle[k][j] == 0) {
if(temp == 0) continue;
container.add(temp);
temp = 0;
}
if(k == N-1) {
if(temp== 0){continue;}
container.add(temp);
}
}
}
// 2-2. ArrayList 에 filter 적용 값이 k인 녀석들만 뽑아 stream list 만들고 그 사이즈를 구한다.
System.out.println("#"+i+" "+container.stream().filter(x -> x == K).count());
container.clear();
}
}
}
풀고 다른 사람들과 내 코드 수를 비교해보니, 내 코드 수가 높은 편에 속해서 그 이유를 알고자 포인트를 내고 다른 사람 코드를 봤다.
2. 다른 사람 코드
import java.util.Scanner;
public class Solution {
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T;
T=sc.nextInt();
/*
여러 개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
*/
for(int test_case = 1; test_case <= T; test_case++)
{
int N = sc.nextInt();
int k = sc.nextInt();
int[][] arr = new int[N][N];
int cnt=0; // 길이가 K인 단어가 들어갈 수 있는 공간 카운팅
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
arr[i][j] = sc.nextInt();
}
}
int cntK=0; // 연속된 1을 담을 그릇, 0을 마주하면 그릇을 다 비우고 다시 받는다.
//가로 검증
for(int i=0; i<N; i++) {
cntK=0;
for(int j=0; j<N; j++) {
if(arr[i][j]==1) {
cntK++;
}else {
if(cntK==k) cnt++; //그릇에 담긴 1이 K개 보다 작은 경우, 많은 경우 다 비운다.
cntK=0;
}
}
if(cntK==k) cnt++;
}
//세로검증
for(int i=0; i<N; i++) {
cntK=0;
for(int j=0; j<N; j++) {
if(arr[j][i]==1) {
cntK++;
}else {
if(cntK==k) cnt++;
cntK=0;
}
}
if(cntK==k) cnt++;
}
System.out.printf("#%d %d\n", test_case, cnt);
}
}
}
나는 연속된 1을 모두 다 ArrayList에 담아서 그 중 K개 인 것만 골라냈는데, 이 코드는 정확히 K개 인 것 제외하고 전부다 버리고 시작한다. 그래서 나랑 코드 수 차이가 났나보다.
'알고리즘 > 문제 풀이' 카테고리의 다른 글
SW Expert Academy 1974. 스도쿠 검증 (0) | 2023.05.14 |
---|---|
Sw Expert Academy 1976. 시각 덧셈 (0) | 2023.05.13 |
SWEA 1983. 조교의 성적 매기기 (0) | 2023.05.11 |
SWEA 1984. 중간 평균값 구하기 (0) | 2023.05.11 |
SWEA 1986. 지그재그 숫자 (0) | 2023.05.11 |