곽로그

[백준 3085, Java] 사탕 게임 renew 본문

알고리즘/백준

[백준 3085, Java] 사탕 게임 renew

일도이동 2021. 3. 23. 00:23
반응형

alwaysbemoon.tistory.com/170

 

[백준 3085, Java] 사탕 게임

문제 www.acmicpc.net/problem/3085 3085번: 사탕 게임 첫째 줄에 상근이가 먹을 수 있는 사탕의 최대 개수를 출력한다. www.acmicpc.net 풀이 1. 행을 순회하면서 인접한/같은 색의 칸을 탐색한다 2. 인접한/ 같.

alwaysbemoon.tistory.com

 

위 포스팅에서 코드를 좀 개선 했다. 

 

좌-우/ 상-하 인접하는 것을 , 동,남방향에 대한 좌표배열을( int[] dr = {0,1,}, int[] dc ={1,0}) 선언해서 for 문으로 합쳤다.

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;



public class Main {
	static int N;
	static char[][] colors;
	static int max = 0;
	static int[] dr = {0,1};
	static int[] dc = {1,0};
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		N = Integer.parseInt(br.readLine());
		colors = new char[N][N];
		
		for(int r = 0; r<N; r++) {
			String line = br.readLine();
			for(int c =0; c<N; c++) {
				colors[r][c] = line.charAt(c);
			}
		}
		
		for(int r=0; r<N; r++) {
			for(int c=0; c<N; c++) {
				for(int d = 0 ;d<2; d++) {
					int nr = r + dr[d];
					int nc = c + dc[d];
					
					if(isValid(nr,nc)) {
						if(colors[r][c]!= colors[nr][nc]) {
							swap(r,c,nr,nc);
							int result = getMax();
							max = Math.max(max, result);
							swap(r,c,nr,nc);
						}
					}
				}
				
			}
		}
		
		bw.write(String.valueOf(max));
		bw.flush();
		
	}	
	public static int getMax() {
		int result = 1;
		
		//행탐색
		for(int r=0; r<N ;r++) {
			char base = colors[r][0];
			int seq = 1;
			for(int c=1; c<N; c++) {
				if(colors[r][c]== base) {
					seq+=1;
				}
				else {
					base = colors[r][c];
					seq = 1;
				}
				
				result = Math.max(result, seq);
			}
		}
		
		
		//행탐색
		for(int c=0; c<N; c++) {
			char base = colors[0][c];
			int seq = 1;
			
			for(int r =1; r<N; r++) {
				if(colors[r][c] == base) {
					seq += 1;
				}
				else {
					base = colors[r][c];
					seq =1;
				}
				
				result = Math.max(result, seq);
			}
		}
		
		
		
		return result;
		
	}
	
	public static void swap(int r1, int c1, int r2, int c2) {
		char temp = colors[r1][c1];
		colors[r1][c1] = colors[r2][c2];
		colors[r2][c2] = temp;
	}
	
	public static boolean isValid(int r, int c) {
		return r<N && c<N;
	}
}
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 15649,Java] N과 M(1) renew  (0) 2021.03.29
[백준 1107, Java] 리모컨  (0) 2021.03.24
[백준 13458, Java] 시험 감독  (0) 2021.03.19
[백준 3190, Java] 뱀  (0) 2021.02.26
[백준 14503, Java] 로봇청소기  (0) 2021.02.25
Comments