|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: (Leetcode) 62 - Unique Paths 풀이 |
| 4 | +categories: [스터디-알고리즘] |
| 5 | +tags: |
| 6 | + [자바, java, 리트코드, Leetcode, 알고리즘, matrix, dynamic programming, dp] |
| 7 | +date: 2024-07-16 15:30:00 +0900 |
| 8 | +toc: true |
| 9 | +--- |
| 10 | + |
| 11 | +기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. |
| 12 | + |
| 13 | +[https://neetcode.io/practice](https://neetcode.io/practice) |
| 14 | + |
| 15 | +--- |
| 16 | + |
| 17 | +[https://leetcode.com/problems/unique-paths/](https://leetcode.com/problems/unique-paths/) |
| 18 | + |
| 19 | +어렸을 때 풀었던 확률 문제가 떠오르는 문제이다. 그 때 했던 풀이 그대로 코드로 옮겨보았다. |
| 20 | + |
| 21 | +## 내가 작성한 풀이 |
| 22 | + |
| 23 | +```java |
| 24 | +class Solution { |
| 25 | + public int uniquePaths(int m, int n) { |
| 26 | + int[][] matrix = new int[m][n]; |
| 27 | + matrix[0][0] = 1; |
| 28 | + |
| 29 | + Deque<Coordinate> deque = new ArrayDeque<>(); |
| 30 | + deque.addLast(new Coordinate(1, 0)); |
| 31 | + deque.addLast(new Coordinate(0, 1)); |
| 32 | + while (!deque.isEmpty()) { |
| 33 | + Coordinate coordinate = deque.removeFirst(); |
| 34 | + if (coordinate.x >= m || coordinate.y >= n || matrix[coordinate.x][coordinate.y] != 0) { |
| 35 | + continue; |
| 36 | + } |
| 37 | + |
| 38 | + int top = coordinate.y > 0 ? matrix[coordinate.x][coordinate.y - 1] : 0; |
| 39 | + int left = coordinate.x > 0 ? matrix[coordinate.x - 1][coordinate.y] : 0; |
| 40 | + matrix[coordinate.x][coordinate.y] = top + left; |
| 41 | + |
| 42 | + deque.addLast(new Coordinate(coordinate.x + 1, coordinate.y)); |
| 43 | + deque.addLast(new Coordinate(coordinate.x, coordinate.y + 1)); |
| 44 | + } |
| 45 | + |
| 46 | + return matrix[m - 1][n - 1]; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class Coordinate { |
| 51 | + int x; |
| 52 | + int y; |
| 53 | + |
| 54 | + public Coordinate(int x, int y) { |
| 55 | + this.x = x; |
| 56 | + this.y = y; |
| 57 | + } |
| 58 | +} |
| 59 | +``` |
| 60 | + |
| 61 | +### TC, SC |
| 62 | + |
| 63 | +시간 복잡도는 `O(m * n)` 공간 복잡도는 `O(m * n)` 이다. |
0 commit comments