본문 바로가기
✏️ CS/자료구조 & 알고리즘

[알고리즘] 시뮬레이션 및 완전탐색 알고리즘

by 개발한 너굴씨 2024. 5. 3.
728x90

 

 

 

 

 

 

자바로 시뮬레이션 및 완전탐색 알고리즘 학습하기


 

 

 

 

 

시뮬레이션과 완전탐색 알고리즘 

시뮬레이션은 주어진 문제를 단계별로 모사하여 해결하는 방식이고, 완전탐색은 가능한 모든 경우를 탐색하여 해를 찾는 방법입니다. 

 

 

 

1. 시뮬레이션 알고리즘

시뮬레이션 알고리즘은 문제의 조건을 단계별로 모사하여 해결하는 방식입니다. 이는 주로 게임, 물리 모델링, 경로 추적 등의 문제에서 사용됩니다.

 

로봇 청소기 시뮬레이션 예제 

로봇 청소기가 주어진 명령어에 따라 방 안을 이동하는 시뮬레이션을 구현해보겠습니다.

문제

  • 방은 2차원 평면으로 주어집니다.
  • 로봇 청소기는 특정 위치에서 시작하며, 주어진 명령어에 따라 상하좌우로 이동합니다.
  • 명령어는 'U'(위), 'D'(아래), 'L'(왼쪽), 'R'(오른쪽)으로 구성됩니다.
public class RobotCleaner {
    public static void main(String[] args) {
        String commands = "UUDDLRLR";
        int[] startPosition = {0, 0};

        int[] finalPosition = simulateMovement(startPosition, commands);
        System.out.println("Final position: (" + finalPosition[0] + ", " + finalPosition[1] + ")");
    }

    public static int[] simulateMovement(int[] position, String commands) {
        int x = position[0];
        int y = position[1];

        for (char command : commands.toCharArray()) {
            switch (command) {
                case 'U': y++; break;
                case 'D': y--; break;
                case 'L': x--; break;
                case 'R': x++; break;
            }
        }

        return new int[]{x, y};
    }
}

 

 

 

 

2. 완전탐색 알고리즘

완전탐색(Brute Force) 알고리즘은 가능한 모든 경우를 탐색하여 문제의 해를 찾는 방식입니다. 이는 주로 작은 문제 공간에서 사용되며, 모든 가능한 조합을 시도하여 최적의 해를 찾습니다.

 

순열 생성 예제 

주어진 숫자 배열의 모든 순열을 생성하는 문제를 해결해보겠습니다.

문제

  • 입력: 숫자 배열
  • 출력: 배열의 모든 순열
import java.util.ArrayList;
import java.util.List;

public class Permutations {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> permutations = generatePermutations(nums);

        System.out.println("All permutations:");
        for (List<Integer> perm : permutations) {
            System.out.println(perm);
        }
    }

    public static List<List<Integer>> generatePermutations(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(result, new ArrayList<>(), nums);
        return result;
    }

    private static void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums) {
        if (tempList.size() == nums.length) {
            result.add(new ArrayList<>(tempList));
        } else {
            for (int i = 0; i < nums.length; i++) {
                if (tempList.contains(nums[i])) continue; // 중복된 숫자는 건너뜁니다.
                tempList.add(nums[i]);
                backtrack(result, tempList, nums);
                tempList.remove(tempList.size() - 1);
            }
        }
    }
}

 

 

 

시뮬레이션과 완전탐색의 장단점

 

장점

  • 단순함 : 시뮬레이션과 완전탐색 알고리즘은 직관적이고 구현이 간단함
  • 확실한 해 : 모든 경우를 탐색하기 때문에 최적의 해를 보장

단점

  • 비효율성 : 가능한 모든 경우를 탐색하기 때문에 시간 복잡도가 매우 높아질 수 있고 큰 문제에서는 비효율적일 수 있음
  • 제약 조건 : 문제의 크기가 커지면 계산 시간이 기하급수적으로 증가하므로, 실제 적용이 어려울 수 있음

 

 

 

 

 

728x90

댓글