Find a differentiable $f$ such that $\mathrm{Zeros}(f)=\mathbb{any\; closed \;set}$ Let $B\subset \mathbb{R}^2$ be a closed set.

How to prove that there is a differentiable function $f:\mathbb{R}^2\longrightarrow\mathbb{R}$ such that $$Z(f)=B$$

where $$Z(f)=\{x\in\mathbb{R}^2:f(x)=0\}$$

Any hints would be appreciated.
I will adapt the  MO answer by Harald Hanche-Olsen, filling in some details, and taking into account that you don't ask for $C^\infty$, but only for a differentiable function.

Let 
$$E_0=\{x\colon\operatorname{dist}(x,B)\ge 1 \}$$
and for $k=1,2,\ldots$ let 
$$E_k=\{x\colon 2^{-k}\le \operatorname{dist}(x,B)\le  2^{1-k}\}$$
These sets cover the complement of $B$. Also let 
$$F_k=\{x\colon  \operatorname{dist}(x,E_k)\le  2^{-k-2}\}$$
be an "enlargement" of $E_k$ which still stays away from $B$.  

Let $\omega$ be a smooth function on $\mathbb R^2$ such that $\omega\ge 0$, $\omega(x)=0$ when $|x|\ge 1/2$, and $\omega(x)&gt;0$ when $|x|\le 1/4$. Let $\omega_k(x) = \omega( 2^{ k}x)$.  

The convolution of $\chi_{F_k}$ with $\omega_k$ has the following properties: 


it is as smooth as $\omega$ is
it is nonnegative
it is zero on the set $ \{x\colon  \operatorname{dist}(x,F_k) &gt;  2^{-k-1}\}$, which contains the set $ \{x\colon  \operatorname{dist}(x,B ) &lt; 2^{-k-2}\}$
it is strictly positive on $E_k$
it does not exceed $4^{-k}\int_{\mathbb R^n} \omega$.


Define
$$f=\sum_{k=0}^\infty  (\chi_{F_k}*\omega_k) \tag{1}$$
and observe that 


$f$ is strictly positive on the complement of $B$, and vanishes   on $B$.
$f$ satisfies an estimate of the form $f(x)\le C(\operatorname{dist}(x,B ))^2$, because at distance about $2^{-k}$ from $B$
it takes values about $4^{-k}$
By the above, $f$ is differentiable on $B$.
$f$ is also differentiable on the complement of $B$, because every point of this complement has a neighborhood in 
which only finitely many terms of (1) are nonzero.




As Harald Hanche-Olsen notes, introducing a rapidly decaying weight one can make the sum $C^\infty$ smooth, e.g.,
$$f=\sum_{k=0}^\infty  2^{-k^2} (\chi_{F_k}*\omega_k )$$
Would something like this work?

Let $B \subset \mathbb{R}^2$ be a closed set. Define a function $f$
$$ f(x) = \text{dist}(x,B)$$
where
$$ \text{dist}(x,B) = \inf_{b\in B} d(x,b)  $$