programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있

programmers.co.kr

DFS 와 BFS 두 가지로 문제를 해결해 봤다.

 

BFS

package eun;

import java.util.*;

public class Solution {
	public static void main(String[] args) {
		int[][] computers  = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
		int n = 3;
		solution(n, computers);
	}
	
	public static int solution(int n, int[][] computers) {
		int answer = 0;
		Queue<Integer> q = new LinkedList<>();
		boolean[] visited = new boolean[n];
		
		// 시작점 for 문
		for (int i=0; i<n; i++) {
			if (!visited[i]) {
				q.add(i);
				
				while(!q.isEmpty()) {
					int cur = q.poll();
					visited[cur] = true;
					
					// 시작점에서 갈 수 있는곳 탐색
					for (int j=0; j<n; j++) {
						if(!visited[j] && computers[cur][j] == 1) q.add(j);
					}
				}
				
				answer++;
			}
		}
		System.out.println(answer);
		return answer;
    }
}

 

DFS

package eun;

public class Eun {
	public static int answer =0;
	public static int[] dx = { 0, 1, 0, -1 };
	public static int[] dy = { 1, 0, -1, 0 };
	public static void main(String[] args) {
		int[][] computers  = {{1, 1, 0}, {1, 1, 0}, {0, 0, 1}};
		//int[][] computers  = {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}};
		int n = 3;
		
		solution(n, computers);
	}
	
	public static int solution(int n, int[][] computers) {
		
        for(int y=0; y<n; y++) {
        	for(int x=0; x<n; x++) {
        		if(computers[y][x] == 1) {
        			dfs(x, y, computers, n);
        			answer++;
        		}
        	}
        }
        System.out.println(answer);
		return answer;
    }
	
	public static void dfs(int x, int y, int[][] computers, int n) {
		computers[y][x] = 0;
		
		for (int i=0; i<4; i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			
			if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
			if (computers[ny][nx] == 0) continue;
			dfs(nx, ny, computers, n);
		}
	}
	
}

 

'Algorithm > solution' 카테고리의 다른 글

[프로그래머스 #level2] 조이스틱.java  (0) 2021.02.23
[HASH] 완주하지 못한 선수  (0) 2019.11.02
#2178. 미로탐색  (0) 2018.12.24
#14503. 로봇 청소기  (1) 2018.01.22
#14891. 톱니바퀴  (0) 2018.01.17

문제 링크

 

코딩테스트 연습 - 조이스틱

조이스틱으로 알파벳 이름을 완성하세요. 맨 처음엔 A로만 이루어져 있습니다. ex) 완성해야 하는 이름이 세 글자면 AAA, 네 글자면 AAAA 조이스틱을 각 방향으로 움직이면 아래와 같습니다. ▲ - 다

programmers.co.kr

그리디(Greedy)

package eun;

// 알파벳은 모두 더하고,
// 이동경로의 최소를 찾는 문제

public class Solution {
	static public int solution(String name) {
        int answer = 0;
        
        int len = name.length();
        
        //최대로 가질 수 있는 min값은 끝까지 가는것
        int min_move = len-1;
        
        for(int i=0; i<len; i++) {
        	answer += Math.min(name.charAt(i)-'A', 'Z'-name.charAt(i)+1);
        	
        	//BEAABA
            //012345
        	
        	//좌우: 연속된 A의 등장에 따라 최소 움직임이 달라진다
        	int next = i+1;// 현재 다음 위치부터
        	//내 다음이 A라면 계속 NEXT++
        	while(next<len && name.charAt(next) == 'A')
        		next++;
        	
        	min_move = Math.min(min_move, i+len-next + i);
        }//for
        
        answer += min_move;
        
        return answer;
    }
	
    
	public static void main(String[] args) {
		System.out.println(solution("BEAABA"));
	}
}

'Algorithm > solution' 카테고리의 다른 글

[프로그래머스 #level3] 네트워크.java  (0) 2021.03.16
[HASH] 완주하지 못한 선수  (0) 2019.11.02
#2178. 미로탐색  (0) 2018.12.24
#14503. 로봇 청소기  (1) 2018.01.22
#14891. 톱니바퀴  (0) 2018.01.17

* 접근 방안

 player를 key값으로, 완주 여부를 value값으로 셋팅하여 완주 여부를 판단 하고자 했습니다.

 

* 문제 해결

 player를 set 할때 1-loop,

 완주 여부를 set할때 1-loop,

 완주 못한 사람은 뽑아낼때 1-loop

 총 3번의 loop를 서칭하게 된다. 이 부분을 어떻게 하면 줄일 수 있을지 고민하였습니다.

 

 고민 끝에

 keySet()를 사용해서 key값을 가져온후(1-loop) value값을 가져오려면(1-loop) 2번의 loop를 돌게 됩니다.  

 이 부분을 entrySet()로 줄일수 있었습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    public static String solution(String[] participant, String[] completion) {
        String answer = "";
        HashMap<String, Integer> hm = new HashMap<>();
        
        for(String player : participant) hm.put(player, hm.getOrDefault(player, 0+ 1);
        for(String finish : completion) hm.put(finish, hm.get(finish) - 1);
        
        for(Map.Entry<String, Integer> map : hm.entrySet()) {
            if(map.getValue() != 0) {
                answer = map.getKey();
            }
        }
        
        return answer;
    }
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

'Algorithm > solution' 카테고리의 다른 글

[프로그래머스 #level3] 네트워크.java  (0) 2021.03.16
[프로그래머스 #level2] 조이스틱.java  (0) 2021.02.23
#2178. 미로탐색  (0) 2018.12.24
#14503. 로봇 청소기  (1) 2018.01.22
#14891. 톱니바퀴  (0) 2018.01.17

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


1. 문제 이해


(0,0) 의 좌표부터 (m,n) 좌표 까지 이동할 때 최소경우의 수를 구하는 문제입니다.


2. 접근 방법


- 완전 탐색을 하되, 갔던곳을 다시 가지 않기 위해 큐를 사용해서 문제를 해결하고자 했습니다.

- 큐가 가지는 자료구조를 만들기 위해 Node라는 클래스를 만들었습니다.


3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package SilverBell;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class NoteString {
    public static int n;
    public static int m;
    public static int result;
    public static int map[][];
    public static int dx[] = { 10-10 };
    public static int dy[] = { 010-1 };
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        
        st = new StringTokenizer(br.readLine());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
        
        map = new int[n][m];
        for(int i=0; i<n; i++) {
            st = new StringTokenizer(br.readLine());
            String tmp = st.nextToken();
            for(int j=0; j<m; j++) {
                map[i][j] = Integer.parseInt(tmp.substring(j, j+1));
            }
        }
        
        bfs(new Node(001));
        System.out.println(result);
    }
    
    public static void bfs(Node init) {
        Queue<Node> qu = new LinkedList<>();
        qu.offer(init);
        
        while(true) {
            if(qu.isEmpty()) break;
            int x = qu.peek().x;
            int y = qu.peek().y;
            int d = qu.peek().depth;
            
            if(x == m-1 && y == n-1) {
                result = d;
                break;
            }
            qu.poll();
            for(int i=0; i<4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                
                if(nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
                if(map[ny][nx] == 0continue;
                
                map[ny][nx] = 0;
                qu.offer(new Node( nx, ny, d+1 ));
            }
        }
    }
}
 
class Node {
    int x, y;
    int depth;
    
    public Node(int x, int y, int depth) {
        this.x = x;
        this.y = y;
        this.depth = depth;
    }
}
cs


'Algorithm > solution' 카테고리의 다른 글

[프로그래머스 #level2] 조이스틱.java  (0) 2021.02.23
[HASH] 완주하지 못한 선수  (0) 2019.11.02
#14503. 로봇 청소기  (1) 2018.01.22
#14891. 톱니바퀴  (0) 2018.01.17
#14502. 연구소  (4) 2018.01.16

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


1. 문제 이해

  

 삼성 기출 문제 입니다. 

 시뮬레이션 문제인데, 과정을 자세히 보면 dfs와는 다른것을 볼 수 있습니다.

처음에 이 문제를 dfs로 접근 하였다가 멘토님의 도움으로 while문으로 해결하는 문제라는것을 깨닳았습니다.


(그러니... 꼭 다시 풀어보자!!)



2. 접근 방법


 문제의 루틴대로 따라가면서 while문을 작성해 봅시다.

여기서 핵심은 flag!!


1) 4방향을 모두 탐색하였는데, 청소할곳(0)을 못찾은 경우에 루틴으로 가기 위한 flag!


2) 뒤로 가봤는데 뒤에가 벽인 경우는 탈출할수 있도록!!


3) 뒤로 가봤는데 뒤에가 벽이 아닌 경우는 방향을 그대로 가져 가도록 합시다!!


위에 3가지를 생각하면서 코딩에 들어가면 문제 끄~~~읏!!!



3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#define MAX_SIZE 50
using namespace std;
 
int dx[] = { 0-101 };
int dy[] = { -1010 };
int n, m;
int map[MAX_SIZE][MAX_SIZE];    // 1:벽, 2:청소
 
int next_dir(int d) {
    return (d + 1) % 4;
}
 
bool map_impossible(int x, int y) {
    if (x < 0 || y < 0 || x >= m || y >= n) return 1;
    return 0;
}
 
int main() {
 
    int r, c, d;
 
    cin >> n >> m;
    cin >> r >> c >> d;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> map[i][j];
        }
    }
 
    int x = c, y = r;
 
    if (d == 1) d = 3;
    else if (d == 3) d = 1;
 
    int res = 0;
    while (true) {
 
        if (map[y][x] == 0) {
            map[y][x] = 2;
            res++;
        }
 
        bool search_flag = false;
 
        for (int i = 0; i < 4; i++) {
            d = next_dir(d);
 
            int nx = x + dx[d];
            int ny = y + dy[d];
 
            if (map_impossible(nx, ny) || map[ny][nx] != 0continue;
 
            x = nx;
            y = ny;
            search_flag = true;
            break;
        }
 
        if (search_flag) continue;
 
        // 4방향 모두 못찾았을 때
 
        d = next_dir(d + 1);    // 뒷 방향
        int nx = x + dx[d];
        int ny = y + dy[d];
 
        if (map_impossible(nx, ny) || map[ny][nx] == 1break;
 
        // 뒤가 벽이 아니면 
        d = next_dir(d + 1);    // 방향 유지한 채
        x = nx;                    // 뒤로 가기
        y = ny;
    }
 
    cout << res << '\n';
    return 0;
}
cs


'Algorithm > solution' 카테고리의 다른 글

[HASH] 완주하지 못한 선수  (0) 2019.11.02
#2178. 미로탐색  (0) 2018.12.24
#14891. 톱니바퀴  (0) 2018.01.17
#14502. 연구소  (4) 2018.01.16
#1953. [모의 SW 역량테스트] 탈주범 검거  (0) 2018.01.07

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


1. 문제 이해


 이 문제를 풀면서 하나 깨닳은 것은 문제 이해가 개인적으로 정말 중요하다는것을 느꼈습니다....

 뱀문제와 마찬가지로 시뮬레이션 문제 입니다.


2. 접근 방법


[1 단계] 입력되는 dir변수에 따라서 시계방향으로 돌지, 반 시계방향으로 돌지 정하게 됩니다.


[2 단계] 왼쪽, 오른쪽을 검사하여 서로 다른 값이 있다면 반대방향으로 돌려주고, 

                                   서로 같은 값이 있다면 돌려 움직이지 않습니다.


=> 저같은 경우는 이 부분을 왼쪽 오른쪽 으로 나눠서 재귀로 작성하였습니다.


cf> 이 부분에서 논리적으로 잘못생각하여 시간이 꽤 걸렸습니다.

 돌리기전에 양옆을 먼저 확인하여 옆 톱니가 움직이는지 여부를 먼저 결정해줘야 합니다!!!


[3 단계] 12시 방향에 있는것들의 가중치를 곱해 답을 출력합니다.


3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <cstdio>
 
using namespace std;
 
int res;
int gear[5][8];
 
void rotate_gear(int n, int d) {
    if (d == 1) {            // 시계방향
        int tmp = gear[n][7];
        for (int i = 6; i >= 0; i--) {
            gear[n][i + 1= gear[n][i];
        }
        gear[n][0= tmp;
    }
    else if (d == -1) {        // 반 시계 방향
        int tmp = gear[n][0];
        for (int i = 1; i < 8; i++) {
            gear[n][i - 1= gear[n][i];
        }
        gear[n][7= tmp;
    }
}
 
void move_right(int n, int d) {
    if (!(1 <= n && n <= 4)) return;
 
    if (gear[n - 1][2!= gear[n][6]) {
        d = (d == 1) ? -1 : 1;
        move_right(n + 1, d);
        rotate_gear(n, d);
    }
}
 
void move_left(int n, int d) {
    if (!(1 <= n && n <= 4)) return;
 
    if (gear[n][2!= gear[n + 1][6]) {
        d = (d == 1) ? -1 : 1;
        move_left(n - 1, d);
        rotate_gear(n, d);
    }
}
 
int main() {
    for (int i = 1; i < 5; i++) {
        for (int j = 0; j < 8; j++) {
            scanf("%1d"&gear[i][j]);
        }
    }
 
    int k;
    scanf("%d"&k);
 
    for (int i = 0; i < k; i++) {
        int bun, dir;
        scanf("%d %d"&bun, &dir);
 
        move_left(bun - 1, dir);
        move_right(bun + 1, dir);
 
        rotate_gear(bun, dir);
    }
 
    res = gear[1][0+ (2 * gear[2][0]) + (4 * gear[3][0]) + (8 * gear[4][0]);
 
    printf("%d\n", res);
    return 0;
}
cs


'Algorithm > solution' 카테고리의 다른 글

#2178. 미로탐색  (0) 2018.12.24
#14503. 로봇 청소기  (1) 2018.01.22
#14502. 연구소  (4) 2018.01.16
#1953. [모의 SW 역량테스트] 탈주범 검거  (0) 2018.01.07
#1759. 암호 만들기  (0) 2017.12.29

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


1. 문제 이해


 벽을 3개 세웠을때, 바이러스가 퍼지고, 그후 바이러스에 전염되지 않은지역을 세는 문제입니다. 이때, 전염되지 않은 지역이 최대가 되는 경우를 알아내는 문제입니다. 


2. 접근 방법


 n이 8보다 작은수 이므로 완전 탐색으로 해결했습니다.


[1단계] dfs로 벽 세우기 (for문을 사용한 완전 탐색)


[2단계] 벽이 3개가 됐을때, bfs로 바이러스 확장시키기


[3단계] 바이러스를 퍼지기 전으로 회복시키면서 전염이 안된 지역 세어주기


3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <cstdio>
#include <vector>
#include <queue>
#define MAX_SIZE 8
 
using namespace std;
 
int n, m;
int dx[] = { 010-1 };
int dy[] = { -1010 };
int map[MAX_SIZE][MAX_SIZE];    // 1:벽, 2:바이러스
int visit[MAX_SIZE][MAX_SIZE];
vector <pair <intint> > virus;
int _max = 0;
 
int recovery_map(int(* a)[MAX_SIZE], int(* b)[MAX_SIZE]) {
    int ret = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (map[i][j] == 0) ret++;
            b[i][j] = a[i][j];
        }
    }
    return ret;
}
 
void copy_map(int(* a)[MAX_SIZE], int (* b)[MAX_SIZE]) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            a[i][j] = b[i][j];
        }
    }
}
 
void bfs() {
    queue <pair<intint> >q;
    for (int i = 0; i < virus.size(); i++) {
        q.push(virus[i]);
    }
    while (!q.empty()) {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
 
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
 
            if (nx < 0 || ny < 0 || nx >= m || ny >= n) continue;
            if (map[ny][nx] != 0continue;
 
            map[ny][nx] = 2;
            q.push(make_pair(nx, ny));
        }
 
    }
}
 
void make_wall(int x, int y, int d) {
    map[y][x] = 1;
    visit[y][x] = 1;
 
    if (d == 3) {
 
        int tmp[MAX_SIZE][MAX_SIZE];
        copy_map(tmp, map);
        bfs();
        int buf = recovery_map(tmp, map);
        _max = _max < buf ? buf : _max;
 
        map[y][x] = 0;
        visit[y][x] = 0;
        return;
    }
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (map[i][j] != 0 || visit[i][j]) continue;
            make_wall(j, i, d + 1);
        }
    }
    map[y][x] = 0;
    visit[y][x] = 0;
 
}
 
int main() {
    scanf("%d %d"&n, &m);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf("%d"&map[i][j]);
            if (map[i][j] == 2) virus.push_back(make_pair(j, i));
        }
    }
 
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (map[i][j] != 0continue;
            make_wall(j, i, 1);
        }
    }
 
    printf("%d\n", _max);
    return 0;
}

cs


'Algorithm > solution' 카테고리의 다른 글

#14503. 로봇 청소기  (1) 2018.01.22
#14891. 톱니바퀴  (0) 2018.01.17
#1953. [모의 SW 역량테스트] 탈주범 검거  (0) 2018.01.07
#1759. 암호 만들기  (0) 2017.12.29
#2140. 지뢰찾기  (0) 2017.12.29

https://www.swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PpLlKAQ4DFAUq


1. 문제 이해


L 시간동안 탈주범이 있을 수 있는 공간의 갯수를 세어보는 문제입니다.


2. 접근 방법


- dfs를 통해 문제에 접근하였습니다.

- 4방향으로 나누어 현재와 다음단계의 파이프를 비교하여 갈수 없는곳을 continue 시켰습니다.

- ret 이라는 변수를 따로 두어 지나간 곳을 1로 체크하여 1이 체크된 곳의 수를 세어 출력하였습니다.


(visit은 ret과 다른 용도 입니다. ret을 쓰지 않으면 갔던곳을 또 갈수 없기 때문에 1번(+)파이프일 경우에 오류가 생기게 됩니다.)


3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string.h>
#define MAX_SIZE 51
 
using namespace std;
 
int map[MAX_SIZE][MAX_SIZE];
bool visit[MAX_SIZE][MAX_SIZE];
bool ret[MAX_SIZE][MAX_SIZE];
int dx[] = { 010-1 };
int dy[] = { -1010 };
 
void dfs(int m, int n, int x, int y, int l, int d) {
    if (d == l) return;
 
    ret[y][x] = 1;
    int cur = map[y][x];
 
    for (int i = 0; i < 4; i++) {
        if (i == 0 && (cur == 3 || cur == 5 || cur == 6)) continue;
        if (i == 1 && (cur == 2 || cur == 6 || cur == 7)) continue;
        if (i == 2 && (cur == 3 || cur == 4 || cur == 7))continue;
        if (i == 3 && (cur == 2 || cur == 4 || cur == 5))continue;
 
        int nx = x + dx[i];
        int ny = y + dy[i];
 
        int next = map[ny][nx];
 
        if (nx < 0 || ny < 0 || nx >= m || ny >= n)continue;
        else if (map[ny][nx] == 0 || visit[ny][nx]) continue;
 
        if (i == 0 && (next == 3 || next == 4 || next == 7)) continue;
        if (i == 1 && (next == 2 || next == 4 || next == 5)) continue;
        if (i == 2 && (next == 3 || next == 5 || next == 6)) continue;
        if (i == 3 && (next == 2 || next == 6 || next == 7)) continue;
        
        visit[y][x] = 1;
        dfs(m, n, nx, ny, l, d + 1);
        visit[y][x] = 0;
    }
}
 
int main() {
    int t;
    cin >> t;
    for (int i = 1; i <= t; i++) {
        int n, m, r, c, l;
        cin >> n >> m >> r >> c >> l;
 
        memset(map, 0sizeof(map));
        memset(ret, falsesizeof(ret));
 
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < m; k++) {
                cin >> map[j][k];
            }
        }
 
        dfs(m, n, c, r, l, 0);
 
        int res = 0;
        for (int j = 0; j < n; j++) {
            for (int k = 0; k < m; k++) {
                if (ret[j][k]) res++;
            }
        }
 
        cout << '#' << i << ' ' << res << '\n';
    }
    return 0;
}
cs


'Algorithm > solution' 카테고리의 다른 글

#14891. 톱니바퀴  (0) 2018.01.17
#14502. 연구소  (4) 2018.01.16
#1759. 암호 만들기  (0) 2017.12.29
#2140. 지뢰찾기  (0) 2017.12.29
#6305. 로또  (0) 2017.12.26

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


1. 문제 이해


 모음 1개와 자음 2개 이상이 꼭 포함 된다는 것을 기억해야 합니다.


2. 접근 방법


로또 (http://sbell92.tistory.com/15?category=640303) 문제와 비슷한 방법으로 접근했습니다.


dfs를 이용해 완전 탐색을 하되, 모음과 자음일 경우를 고려해 주었습니다.



3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <algorithm>
#include <iostream>
#include <vector>
#define MAX_SIZE 20
 
using namespace std;
 
int l, c, ja, mo;
vector<char> res;
 
void dfs(vector<char>& v, int d, int cnt) {
    if (l == cnt && mo >= 1 && ja >= 2) {
        for (int i = 0; i < res.size(); i++) {
            cout << res[i];
        }
        cout << '\n';
        return;
    }
    if (l == cnt) return;        // 모음, 자음 만족 안하고 길이가 l이 될때
    if (c == d) return;            // 완전히 탐색했을때
 
    if (v[d] == 'a' || v[d] == 'e' || v[d] == 'i' || v[d] == 'o' || v[d] == 'u') {
        mo++;
    }
    else {
        ja++;
    }
 
    res.push_back(v[d]);
    dfs(v, d + 1, cnt + 1);
 
    char out = res.back();
    if (out == 'a' || out == 'e' || out == 'i' || out == 'o' || out == 'u') {
        mo--;
    }
    else {
        ja--;
    }
    res.pop_back();
    dfs(v, d + 1, cnt);
}
 
int main() {
    cin >> l >> c;
 
    char input;
    vector<char> v;
    for (int i = 0; i < c; i++) {
        cin >> input;
        v.push_back(input);
    }
    sort(v.begin(), v.end());
 
    dfs(v, 00);
 
    return 0;
}
cs


※ 오늘의 코드 리뷰 : 벡터가 점점 익숙해져 갑니다. ㅎㅎ

'Algorithm > solution' 카테고리의 다른 글

#14502. 연구소  (4) 2018.01.16
#1953. [모의 SW 역량테스트] 탈주범 검거  (0) 2018.01.07
#2140. 지뢰찾기  (0) 2017.12.29
#6305. 로또  (0) 2017.12.26
#1463. 1로 만들기  (0) 2017.12.24

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


1. 문제 이해


 길이가 n인 정사각형의 맨 밖깥 부분에만 숫자가 써져 있고 그 안에는 #으로 지뢰가 가려져 있습니다. 

지뢰가 최대로 있을 경우를 구하는 문제입니다.


2. 접근 방법


 #부분을 공략하는 것이 이 문제의 point 입니다.


1. # 부분을 완전 탐색 합니다.

2. #부분의 8방향에 0이 하나라도 있다면 # 부분에는 지뢰가 없습니다.

3. #부분의 8방향이 0이 하나도 업다면 카운트를 올려주고, 주변 8방향을 -1 해줍니다.


3. 문제 해결


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <string>
#include <iostream>
#include <vector>
#include <cstdio>
#define MAX_SIZE 105
 
using namespace std;
 
int dx[] = { -101-11-101 };
int dy[] = { -1-1-100111 };
int map[MAX_SIZE][MAX_SIZE];
 
void find_bomb(int x, int y, int& cnt) {
    bool flag = true;        // 0이 없으면 true
    for (int i = 0; i < 8; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
 
        if (map[ny][nx] == 0) {
            flag = false;
            break;
        }
    }
 
    if (flag) {
        cnt++;
        for (int i = 0; i < 8; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
 
            if(map[ny][nx] > 0)    map[ny][nx] -= 1;
        }
    }
}
 
int main() {
    int n;
    scanf("%d"&n);
 
    vector <string> input(n);
    for (int i = 0; i < n; i++) {
        cin >> input[i];
        for (int j = 0; j < n; j++) {
            map[i][j] = input[i][j] - 48;
        }
    }
    
    int cnt = 0;
 
    if (n == 3) {
        find_bomb(11, cnt);
    }
    else if (n > 3) {
        for (int i = 1; i <= n - 2; i++) {
            for (int j = 1; j <= n - 2; j++) {
                find_bomb(j, i, cnt);
            }
        }
    }
 
    printf("%d\n", cnt);
 
    return 0;
}
cs


'Algorithm > solution' 카테고리의 다른 글

#1953. [모의 SW 역량테스트] 탈주범 검거  (0) 2018.01.07
#1759. 암호 만들기  (0) 2017.12.29
#6305. 로또  (0) 2017.12.26
#1463. 1로 만들기  (0) 2017.12.24
#10815. 숫자카드  (0) 2017.12.24

+ Recent posts