Replies: 2 comments 4 replies
-
제가 저번주에 했던 이야기의 요지는 아래와 같고, 제가 이해하고 있는 시간복잡도의 개념은 이 글에 설명하였습니다 :D class Solution(object):
def exist(self, board, word):
rows, cols = len(board), len(board[0])
visit = [[False] * cols for _ in range(rows)]
def word_search(i, j, idx):
# word를 찾은 경우 True 반환하며 탈출
if idx == len(word):
return True
# 현재 탐색하려는 좌표에서 False를 반환하는 경우
# 유의미한 연산을 진행하지 않으므로 시간 복잡도 계산에서 제외되어도 무방하다고 생각함
if i < 0 or i >= rows or j < 0 or j >= cols:
return False
if board[i][j] != word[idx]:
return False
if visit[i][j]:
return False
# 그 외의 경우엔 word_search 함수를 현재 좌표로부터 3방향으로 재귀 호출
# 코드 상으로는 4방향으로 호출하는 것처럼 보이지만
# word_search 첫번째 호출을 제외하면 3방향으로만 재귀 호출한다고 봐야 한다고 생각함
# 왜냐하면 그 전에 방문했던 좌표는 방문해도 바로 False를 반환하기 때문
# 따라서 word의 길이 k가 증가함에 따라 재귀 호출의 수는 3^k 꼴로 증가할 것임
visit[i][j] = True
next_idx = idx + 1
if (word_search(i + 1, j, next_idx) or
word_search(i - 1, j, next_idx) or
word_search(i, j + 1, next_idx) or
word_search(i, j - 1, next_idx)
):
return True
visit[i][j] = False
return False
for i in range(rows):
for j in range(cols):
if word_search(i, j, 0):
return True
return False 따라서 해당 코드의 실행시간
시간 복잡도는 |
Beta Was this translation helpful? Give feedback.
-
이 문제도 면접관과 긴밀한 협의가 필요할 것 같습니다 // 0, 1로 이루어진 매우 큰 배열로 가정
const arr = [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0... ];
function someAlgorithm(arr: number[]): number {
let result = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 1) {
for (let j = 0; j < arr.length; j++) {
result += arr[j];
}
}
}
return result;
} 위 함수는 명확히 이 코드의 경우:
라는 느낌인 반면,
따라서 입력과 상관없이 탐색의 복잡도는 이 점에서 보면, |
Beta Was this translation helpful? Give feedback.
-
Word Search을
DFS
방식을 이용하여 풀 경우의 시간 복잡도에 대해서 이야기 합니다.4주차 모임에서
Word Search
문제 발표자셨던 @TonyKim9401 님의python
코드입니다.Beta Was this translation helpful? Give feedback.
All reactions