[알고리즘] 파리퇴치3

2024. 1. 1. 16:07알고리즘 풀이/Java

나의 풀이

- 이차원 배열 타입이 int[][]라는 것을 배웠다.

- {}로 값을 배열 값을 초기화하는 것을 배웠다.

- 클래스 내부 메소드를 사용할 수 있도록 하기 위해서는 static이 붙어야 한다는 것을 배웠다.

- for 문으로 탐색도 할 수 있음을 배웠다.

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

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 m = sc.nextInt();
            
            int[][] flys = new int[n][n];
			for (int i = 0; i < n; i++) {
            	for (int j = 0; j < n; j++) {
                	flys[i][j] = sc.nextInt();    
                }
            }
            
            // +
            int[] plusDx = {0, 0, -1, 1};
            int[] plusDy = {-1, 1, 0, 0};
            int plusShapeMaxCatched = findMaxCatched(flys, plusDx, plusDy, n, m);
            
            // x
            int[] xDx = {-1, -1, 1, 1};
            int[] xDy = {-1, 1, -1, 1};
            int xShapeMaxCatched = findMaxCatched(flys, xDx, xDy, n, m);
            
            int totalCatched = Math.max(plusShapeMaxCatched, xShapeMaxCatched);
            System.out.println("#" + test_case + " " + totalCatched);
		}
	}
    
    private static int findMaxCatched(int[][] flys, int[] dx, int[] dy, int n, int m) {
        int max_catched = Integer.MIN_VALUE;
        for (int x = 0; x < n; x++) {
            	for (int y = 0; y < n; y++) {
                    	int catched = flys[y][x];
                	    for (int ct = 1; ct < m; ct++) {
                            for (int turn = 0; turn < 4; turn++) {
                        		int indexX = x + dx[turn] * ct;
	                            int indexY = y + dy[turn] * ct;
                                
                                if (indexX >=0 && indexX < n && indexY >=0 && indexY < n) {
                                	catched += flys[indexY][indexX];
                                }
                            }
                        }
                    	max_catched = Math.max(max_catched, catched);
                }
            }
        
        return max_catched;
    }
}

 

https://swexpertacademy.com/main/code/userProblem/userProblemDetail.do?contestProbId=AXuARWAqDkQDFARa

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

Reference


https://code-master-s.tistory.com/38

 

[SWEA] 12712 - 파리퇴치 3 (자바/Java)

https://swexpertacademy.com/main/code/userProblem/userProblemDetail.do?contestProbId=AXuARWAqDkQDFARa 이차원 배열의 사방탐색과 팔방탐색 유형이다. 먼저 +형태를 훑고, 그 다음 x형태를 훑으며 가장 큰 sum의 값을 업데

code-master-s.tistory.com

 

'알고리즘 풀이 > Java' 카테고리의 다른 글

[알고리즘] 두 개의 숫자열  (1) 2024.01.01
[알고리즘] 최빈수 구하기  (0) 2024.01.01
[알고리즘] 자릿수 더하기  (0) 2023.12.31
[알고리즘] 중간값 찾기  (0) 2023.12.31
[알고리즘] 1대1 가위바위보  (1) 2023.12.31