{ "cells": [ { "cell_type": "markdown", "source": [ "Given an ` _m_ x _n_` matrix. If an element is **0** , set its entire row and\n", "column to **0**. Do it [**in-place**](https://en.wikipedia.org/wiki/In-\n", "place_algorithm).\n", "\n", "**Follow up:**\n", "\n", " * A straight forward solution using O( _m_ _n_ ) space is probably a bad idea.\n", " * A simple improvement uses O( _m_ \\+ _n_ ) space, but still not the best solution.\n", " * Could you devise a constant space solution?\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "![](https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg)\n", "\n", "\n", "\n", " Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]\n", " Output: [[1,0,1],[0,0,0],[1,0,1]]\n", "\n", "\n", "**Example 2:**\n", "\n", "![](https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg)\n", "\n", "\n", "\n", " Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\n", " Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]\n", "\n", "\n", "\n", "\n", "**Constraints:**\n", "\n", " * `m == matrix.length`\n", " * `n == matrix[0].length`\n", " * `1 <= m, n <= 200`\n", " * `-231 <= matrix[i][j] <= 231 - 1`" ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "set_zeroes (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function set_zeroes(matrix::Vector{Vector{Int}})::Vector{Vector{Int}}\n", " is_col = false\n", " m, n = length(matrix), length(matrix[1])\n", "\n", " for i = 1:m\n", " matrix[i][1] == 0 && (is_col = true)\n", "\n", " for j = 2:n\n", " matrix[i][j] == 0 && (matrix[i][1] = matrix[1][j] = 0)\n", " end\n", " end\n", "\n", " for i = 2:m, j = 2:n\n", " (matrix[i][1] == 0 || matrix[1][j] == 0) && (matrix[i][j] = 0)\n", " end\n", "\n", " # See if the first row needs to be set to zero as well\n", " if matrix[1][1] == 0\n", " for j = 1:n\n", " matrix[1][j] = 0\n", " end\n", " end\n", "\n", " # See if the first column needs to be set to zero as well\n", " if is_col\n", " for i = 1:m\n", " matrix[i][1] = 0\n", " end\n", " end\n", "\n", " return matrix\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }