-
Notifications
You must be signed in to change notification settings - Fork 0
542. 01 Matrix #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ryosuketc
wants to merge
5
commits into
main
Choose a base branch
from
542_01_matrix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
542. 01 Matrix #27
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # 542. 01 Matrix | ||
|
|
||
| https://leetcode.com/problems/01-matrix/ | ||
|
|
||
| ## Comments | ||
|
|
||
| ### step1 | ||
|
|
||
| * 5:00 くらい考えた | ||
| * 最短経路なので、BFS あたりで解けそう | ||
| * `1 <= m, n <= 10^4` なので、愚直に 1 から初めて最も近い 0 を探すとなると、O((m * n)^2) になり、10^16? さすがに C++ でも通らないな… | ||
| * 0 から始めるとどうかな。複数の 1 を一気に更新できるから効率は良さそう | ||
| * このあたりまで考えて 5:00 くらい。本当にこの方針でいいのか自信がなかったのと、実装が割と煩雑になりそうだったのでハマる前に答えを見ることにした。 | ||
| * `1 <= m * n <= 10^4` を見逃していた。セルの数自体も 10^4 なのか。なら 10^8 くらいに収まるから行けるか | ||
| * BFS だと最初の訪問 == 最短経路になる。0 から初めて visited かどうかを管理しておくと、結局それぞれのセルは 1 回ずつしか訪れないので O(m * n) のオーダーに収まる。 | ||
| * 1 から始めると、BFS しても途中で訪問したセルの最短距離は確定しないのでややこしい | ||
| * 答えを見る前に、0 から始めるか 1 から始めるかの選択肢を持てていたのは良かった。しかし runtime の観点できれいに考えを整理できていなかった。また実装方法についても具体的に頭の中でシミュレーションできていなかったので答えに頼ることになった | ||
| * 答えも参考に書いてみた。 | ||
| * まあ素直な書き方なのだが、上記実装を具体的に考えられていなかったのは、最初に前処理として 0 を queue に突っ込んでおく、というのを考えられていなかったからだと思われる。 | ||
| * あとは割と素直な BFS | ||
| * `distance` の命名は `steps` でもよかったかもしれない | ||
| * vector 変数の初期化でサイズ指定などを忘れていた。今までは `push_back` していくだけのものが多かったので失念。 | ||
|
|
||
| ```cpp | ||
| vector<vector<int>> distances(rows, vector<int>(cols, 0)); | ||
| vector<vector<bool>> visited(rows, vector<bool>(cols, false)); | ||
| ``` | ||
|
|
||
| ### step2 | ||
|
|
||
| * https://leetcode.com/problems/01-matrix/editorial/ | ||
| * あまりしっかり見れてはいない (TODO) のだが、DP での解法もあるみたい。まあ確かにできそうではある。 | ||
| * https://github.com/huyfififi/coding-challenges/pull/27 | ||
| * BFS で問題ないと思うのだが、`leetcode/542/step1_two_pass.py` の解答を一応 C++ で書き直してみた。 | ||
| * 最初 `numeric_limits` をそのまま使っていたのだが、+1 するケースがあり、そうすると overflow する。Gemini に進められたのでそのようにしてみた。でもこれ prod ではやりたくないな… 10000 という数字の選定も適当だし。 | ||
| * この解法、気持ちだけ DP っぽい雰囲気もする (前に確定した情報を使って次を更新していく) | ||
|
|
||
| ### step3 | ||
|
|
||
| * skip | ||
| * 最終解答 (面接や prod だとしたら) としては step1 の BFS かなと思う |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| #include <queue> | ||
|
|
||
| class Solution { | ||
| public: | ||
| vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { | ||
| int rows = mat.size(); | ||
| int cols = mat[0].size(); | ||
| vector<vector<int>> distances(rows, vector<int>(cols, 0)); | ||
| vector<vector<bool>> visited(rows, vector<bool>(cols, false)); | ||
| std::queue<vector<int>> cells_and_distances; | ||
| // Add zeros to the queue. | ||
| for (int row = 0; row < rows; ++row) { | ||
| for (int col = 0; col < cols; ++col) { | ||
| distances[row][col] = 0; | ||
| if (mat[row][col] == 0) { | ||
| cells_and_distances.push({row, col, 0}); | ||
| visited[row][col] = true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // BFS traversal | ||
| while (!cells_and_distances.empty()) { | ||
| vector<int> info = cells_and_distances.front(); | ||
| cells_and_distances.pop(); | ||
| int row = info[0]; | ||
| int col = info[1]; | ||
| int distance = info[2]; | ||
| for (vector<int>& direction : directions) { | ||
| int next_row = row + direction[0]; | ||
| int next_col = col + direction[1]; | ||
| if (!IsValid(next_row, next_col, rows, cols) || visited[next_row][next_col]) { | ||
| continue; | ||
| } | ||
| distances[next_row][next_col] = distance + 1; | ||
| visited[next_row][next_col] = true; | ||
| cells_and_distances.push({next_row, next_col, distance + 1}); | ||
| } | ||
| } | ||
|
|
||
| return distances; | ||
| } | ||
| private: | ||
| vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; | ||
|
|
||
| bool IsValid(int row, int col, int rows, int cols) { | ||
| return 0 <= row && row < rows && 0 <= col && col < cols; | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| #include <vector> | ||
| #include <algorithm> | ||
|
|
||
| using namespace std; | ||
|
|
||
| class Solution { | ||
| public: | ||
| vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { | ||
| int rows = mat.size(); | ||
| // if (rows == 0) return mat; | ||
| int cols = mat[0].size(); | ||
| // Use a safe "infinity" that won't overflow when adding 1 | ||
| int INF = numeric_limits<int>::max() - 10000; | ||
| // Initialization: Set non-zero cells to inf. | ||
| for (int row = 0; row < rows; ++row) { | ||
| for (int col = 0; col < cols; ++col) { | ||
| if (mat[row][col] != 0) { | ||
| mat[row][col] = INF; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // First pass: Check top and left neighbors | ||
| for (int row = 0; row < rows; ++row) { | ||
| for (int col = 0; col < cols; ++col) { | ||
| if (mat[row][col] == 0) { | ||
| continue; | ||
| } | ||
|
|
||
| if (row > 0) { | ||
| // top (up) | ||
| mat[row][col] = min(mat[row][col], mat[row - 1][col] + 1); | ||
| } | ||
| if (col > 0) { | ||
| // left | ||
| mat[row][col] = min(mat[row][col], mat[row][col - 1] + 1); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Second pass: Check bottom and right neighbors (iterate backwards) | ||
| for (int row = rows - 1; row >= 0; --row) { | ||
| for (int col = cols - 1; col >= 0; --col) { | ||
| if (mat[row][col] == 0) { | ||
| continue; | ||
| } | ||
|
|
||
| if (row < rows - 1) { | ||
| // bottom (down) | ||
| mat[row][col] = min(mat[row][col], mat[row + 1][col] + 1); | ||
| } | ||
| if (col < cols - 1) { | ||
| // right | ||
| mat[row][col] = min(mat[row][col], mat[row][col + 1] + 1); | ||
| } | ||
| } | ||
| } | ||
| return mat; | ||
| } | ||
| }; | ||
Empty file.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
全体的に読みやすく勉強になりました。
最代入しない変数のであれば、const を付けても良いと思いました。