[宽度优先搜索] leetcode 773 Sliding Puzzle
problem:https://leetcode.com/problems/sliding-puzzle/
一看到求最短次数就是宽搜了。用字符串来记录所有状态量即可,找到目标状态量后就退出,我们总能保证找到时用到的步数是最少的。
class Solution { public: int slidingPuzzle(vector<vector<int>>& board) { queue<string> q; string begin; int m = board.size(); int n = board[0].size(); for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[i].size(); j++) { begin.push_back(board[i][j] + '0'); } } int res = 0; q.push(begin); bool bFind = false; vector<int> dx{ 0,1,0,-1 }; vector<int> dy{ 1,0,-1,0 }; unordered_set<string> visit; while (!q.empty()) { int size = q.size(); while (size--) { string cur = q.front(); q.pop(); if (cur == "123450") { bFind = true; break; } size_t pos = cur.find('0'); int i = pos / n; int j = pos % n; for (int k = 0; k < 4; k++) { int x = i + dx[k]; int y = j + dy[k]; if (x >= 0 && y >= 0 && x < m && y < n) { int newPos = x * n + y; string next = cur; swap(next[pos], next[newPos]); if (visit.find(next) == visit.end()) { visit.insert(next); q.push(next); } } } } if (bFind) break; res++; } if (!bFind) return -1; return res; } };

浙公网安备 33010602011771号