LeetCode //C - 752. Open the Lock

752. Open the Lock

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’. The wheels can rotate freely and wrap around: for example we can turn ‘9’ to be ‘0’, or ‘0’ to be ‘9’. Each move consists of turning one wheel one slot.

The lock initially starts at ‘0000’, a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
 

Example 1:

Input: deadends = [“0201”,“0101”,“0102”,“1212”,“2002”], target = “0202”
Output: 6
Explanation:
A sequence of valid moves would be “0000” -> “1000” -> “1100” -> “1200” -> “1201” -> “1202” -> “0202”.
Note that a sequence like “0000” -> “0001” -> “0002” -> “0102” -> “0202” would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end “0102”.

Example 2:

Input: deadends = [“8888”], target = “0009”
Output: 1
Explanation: We can turn the last wheel in reverse to move from “0000” -> “0009”.

Example 3:

Input: deadends = [“8887”,“8889”,“8878”,“8898”,“8788”,“8988”,“7888”,“9888”], target = “8888”
Output: -1
Explanation: We cannot reach the target without getting stuck.

Constraints:
  • 1 <= deadends.length <= 500
  • deadends[i].length == 4
  • target.length == 4
  • target will not be in the list deadends.
  • target and deadends[i] consist of digits only.

From: LeetCode
Link: 752. Open the Lock


Solution:

Ideas:

1. Create a hash set of deadends for O(1) lookup

2. Check edge cases (starting at deadend or already at target)

3. Use BFS starting from “0000”:

  • For each state, generate all 8 possible next moves
  • Skip deadends and already visited states
  • If target is reached, return the move count
  • Otherwise, add valid states to queue and mark as visited

4. Time Complexity: O(10^4) in worst case since there are at most 10,000 possible states (0000-9999)

5. Space Complexity: O(10^4) for the queue, visited set, and deadend set

Code:
// Queue structure for BFS
typedef struct {
    char state[5];
    int moves;
} QueueNode;

typedef struct {
    QueueNode* data;
    int front;
    int rear;
    int capacity;
} Queue;

Queue* createQueue(int capacity) {
    Queue* q = (Queue*)malloc(sizeof(Queue));
    q->data = (QueueNode*)malloc(capacity * sizeof(QueueNode));
    q->front = 0;
    q->rear = 0;
    q->capacity = capacity;
    return q;
}

void enqueue(Queue* q, char* state, int moves) {
    strcpy(q->data[q->rear].state, state);
    q->data[q->rear].moves = moves;
    q->rear++;
}

QueueNode dequeue(Queue* q) {
    return q->data[q->front++];
}

bool isEmpty(Queue* q) {
    return q->front == q->rear;
}

void freeQueue(Queue* q) {
    free(q->data);
    free(q);
}

// Hash set for visited states and deadends
#define HASH_SIZE 10007

typedef struct HashNode {
    char state[5];
    struct HashNode* next;
} HashNode;

typedef struct {
    HashNode* buckets[HASH_SIZE];
} HashSet;

int hash(char* state) {
    int h = 0;
    for (int i = 0; i < 4; i++) {
        h = h * 10 + (state[i] - '0');
    }
    return h % HASH_SIZE;
}

HashSet* createHashSet() {
    HashSet* set = (HashSet*)malloc(sizeof(HashSet));
    for (int i = 0; i < HASH_SIZE; i++) {
        set->buckets[i] = NULL;
    }
    return set;
}

void addToHashSet(HashSet* set, char* state) {
    int h = hash(state);
    HashNode* node = (HashNode*)malloc(sizeof(HashNode));
    strcpy(node->state, state);
    node->next = set->buckets[h];
    set->buckets[h] = node;
}

bool containsInHashSet(HashSet* set, char* state) {
    int h = hash(state);
    HashNode* node = set->buckets[h];
    while (node) {
        if (strcmp(node->state, state) == 0) {
            return true;
        }
        node = node->next;
    }
    return false;
}

void freeHashSet(HashSet* set) {
    for (int i = 0; i < HASH_SIZE; i++) {
        HashNode* node = set->buckets[i];
        while (node) {
            HashNode* temp = node;
            node = node->next;
            free(temp);
        }
    }
    free(set);
}

// Generate next states by turning one wheel up or down
void getNextStates(char* current, char nextStates[][5]) {
    int count = 0;
    
    for (int i = 0; i < 4; i++) {
        // Turn wheel i up
        strcpy(nextStates[count], current);
        if (nextStates[count][i] == '9') {
            nextStates[count][i] = '0';
        } else {
            nextStates[count][i]++;
        }
        count++;
        
        // Turn wheel i down
        strcpy(nextStates[count], current);
        if (nextStates[count][i] == '0') {
            nextStates[count][i] = '9';
        } else {
            nextStates[count][i]--;
        }
        count++;
    }
}

int openLock(char** deadends, int deadendsSize, char* target) {
    // Create hash set for deadends
    HashSet* deadendSet = createHashSet();
    for (int i = 0; i < deadendsSize; i++) {
        addToHashSet(deadendSet, deadends[i]);
    }
    
    // Check if starting position is a deadend
    if (containsInHashSet(deadendSet, "0000")) {
        freeHashSet(deadendSet);
        return -1;
    }
    
    // Check if we're already at target
    if (strcmp("0000", target) == 0) {
        freeHashSet(deadendSet);
        return 0;
    }
    
    // BFS setup
    Queue* queue = createQueue(10000);
    HashSet* visited = createHashSet();
    
    enqueue(queue, "0000", 0);
    addToHashSet(visited, "0000");
    
    while (!isEmpty(queue)) {
        QueueNode current = dequeue(queue);
        
        // Generate all possible next states
        char nextStates[8][5];
        getNextStates(current.state, nextStates);
        
        for (int i = 0; i < 8; i++) {
            // Skip if this state is a deadend
            if (containsInHashSet(deadendSet, nextStates[i])) {
                continue;
            }
            
            // Skip if already visited
            if (containsInHashSet(visited, nextStates[i])) {
                continue;
            }
            
            // Check if we reached the target
            if (strcmp(nextStates[i], target) == 0) {
                int result = current.moves + 1;
                freeQueue(queue);
                freeHashSet(visited);
                freeHashSet(deadendSet);
                return result;
            }
            
            // Add to queue and mark as visited
            enqueue(queue, nextStates[i], current.moves + 1);
            addToHashSet(visited, nextStates[i]);
        }
    }
    
    // Target not reachable
    freeQueue(queue);
    freeHashSet(visited);
    freeHashSet(deadendSet);
    return -1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值