2차원배열

채종윤·2023년 7월 16일

문제

https://www.acmicpc.net/status?user_id=cjy205&problem_id=10798&from_mine=1

내풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class B10798 {
	public static void main(String[] args) throws IOException {
		BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
		
		char[][] arr = new char[5][15];
		String line;
		
		int max =0;
		for (int i = 0; i < arr.length; i++) {
			line = br.readLine();
			if(max < line.length())
					{
				max = line.length();
			}
			for (int j = 0; j < line.length(); j++) {
				arr[i][j] = line.charAt(j);
				
			}
		}
		
		for (int i = 0; i < max; i++) {
			for (int j = 0; j < 5; j++) {
				if(arr[j][i]=='\0')continue;
				System.out.print(arr[j][i]);
			}
			
		}
	}
}

해결방법:

char 배열의 초기 값은 '\0' 이다. 따라서 '\0'이면 continue를 해줌.
max변수를 선언해줘서 가장 길이 수가 긴걸 알아야함

문제

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

내풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;


public class B2563 {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int[][] arr = new int[100][100];
		int count= 0;
		StringTokenizer st ;
		
		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());
			
			for (int j = x; j < x+10; j++) {
				for (int k = y; k < y+10; k++) {
					arr[j][k] =1;		
				}
			}
		}
		
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length; j++) {
				if(arr[i][j]==1) count++;		
			}		
		}
		System.out.println(count);
	}
}

해설 :
넓이를 구할때는 좌표로 계산하기 보다는 1의개수를 카운팅해줘서 구하는게 좋음
또한 가장 많이 겹치는 장수를 구하고 싶으면
arr[j][k] += arr[j][k]를 해주면 됨

profile
안녕하세요. 백앤드 개발자를 목표로 하고 있습니다!

0개의 댓글