Personalize o tamanho da caixa de desenho na matriz

Personalize o tamanho da caixa de desenho na matriz
\documentclass{beamer}
\usetheme{Madrid}
\usepackage{amsmath,tikz}
\usetikzlibrary{matrix}

\begin{document}
\begin{frame}{Matrix}

This is an example of a matrix.

\begin{tikzpicture}
\matrix [matrix of math nodes,left delimiter=(,right delimiter=),ampersand replacement=\&] (m)
{
  8 \& 8 \& 1 \& 6 \\
  3 \& 8 \& 5 \& 7 \\
  4 \& 8 \& 9 \& 5 \\
};
\draw[color=red, thick] (m-1-1.north west) -- (m-1-3.north east) -- (m-2-3.south east) -- (m-2-1.south west) -- (m-1-1.north west);
\draw[color=blue, thick] (m-2-1.north west) -- (m-2-3.north east) -- (m-3-3.south east) -- (m-3-1.south west) -- (m-2-1.north west);
\end{tikzpicture}
\end{frame}
\end{document}

Desenhei duas caixas em uma matriz (no Beamer). Funciona, exceto que as duas caixas se sobrepõem parcialmente e, portanto, a caixa azul é colocada parcialmente sobre a caixa vermelha, o que não é muito bonito.

Existe uma maneira de aumentar ou diminuir a caixa azul, para que elas não se sobreponham? (Outras formas de evitar a sobreposição também são bem-vindas.)

Responder1

Suponhamos que você espere algo assim:

insira a descrição da imagem aqui

\documentclass{beamer}
\usetheme{Madrid}
\usepackage{amsmath,tikz}
\usetikzlibrary{fit,matrix}
\tikzset{
mN/.style = {%myNode
    draw=#1, thick, inner sep=0pt}
             }

\begin{document}
\begin{frame}{Matrix}

This is an example of a matrix.

    \begin{tikzpicture}
\matrix [matrix of math nodes, column sep=1pt,
         left delimiter=(,right delimiter=),ampersand replacement=\&] (m)
{
  8 \& 8 \& 1 \& 6 \\
  3 \& 8 \& 5 \& 7 \\
  4 \& 8 \& 9 \& 5 \\
};
\node[mN=red, xshift= 2pt, fit=(m-1-1) (m-2-3)] {};
\node[mN=blue,xshift=-2pt, fit=(m-2-1) (m-3-3)] {};
\end{tikzpicture}
\end{frame}
    \end{document}

Editar:Otimizei um pouco o código.

informação relacionada