From ee8def9d6b460ecb0a3b5ac31b386677a5af5c30 Mon Sep 17 00:00:00 2001 From: chunyang Date: Mon, 20 Jul 2020 07:04:46 +0800 Subject: [PATCH] add minmum steps to reach --- minimum-steps-to-reach.cpp | 79 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 minimum-steps-to-reach.cpp diff --git a/minimum-steps-to-reach.cpp b/minimum-steps-to-reach.cpp new file mode 100644 index 0000000..cefef04 --- /dev/null +++ b/minimum-steps-to-reach.cpp @@ -0,0 +1,79 @@ +#include +#include +#include + +using namespace std; + +typedef pair Pos; + + +int minimum_steps(const vector>& m, pair s, pair e) { + + int row = m.size(); + int col = m[0].size(); + vector> distance(row, vector(col, -1)); + distance[s.first][s.second] = 0; + vector st; + vector next_st; + int step = 1; + st.push_back(s); + int limit = row * col; + while (distance[e.first][e.second] == -1 && step < limit) { + + while (!st.empty()) { + auto b = st.back(); st.pop_back(); + + // right + Pos p = make_pair(b.first, b.second+1); + if (p.second < col && !m[p.first][p.second]) { + if (distance[p.first][p.second] == -1) { + distance[p.first][p.second] = step; + next_st.push_back(p); + } + } + + // left + p = make_pair(b.first, b.second-1); + if (p.second >= 0 && !m[p.first][p.second]) { + if (distance[p.first][p.second] == -1) { + distance[p.first][p.second] = step; + next_st.push_back(p); + } + } + + + // top + p = make_pair(b.first-1, b.second); + if (p.first >= 0 && !m[p.first][p.second]) { + if (distance[p.first][p.second] == -1) { + distance[p.first][p.second] = step; + next_st.push_back(p); + } + } + + // bottom + p = make_pair(b.first+1, b.second); + if (p.first < row && !m[p.first][p.second]) { + if (distance[p.first][p.second] == -1) { + distance[p.first][p.second] = step; + next_st.push_back(p); + } + } + } + st.swap(next_st); + ++step; + } + + return distance[e.first][e.second]; +} + +int main() { + vector> m{ + {false, false, false, false}, + {true, true, false, true}, + {false, false, false, false}, + {false, false, false, false} + }; + cout << minimum_steps(m, {3 ,0}, {0, 0}) << endl; + return 0; +}