lego[(x_)?MatrixQ, y___Rule] := 
  Module[{imax, jmax, min}, {imax, jmax} = Dimensions[x]; min = Min[x]; 
    Show[Graphics3D[Flatten[Table[cube[i, j, imax, jmax, min, x], {i, imax}, 
        {j, jmax}]], Axes -> True, 
      PlotRange -> {{1/2, imax + 1/2}, {1/2, jmax + 1/2}, 
       {min, Max[x]*1.001-min*0.001}}, y]]]
 
lego[(x_)?MatrixQ, (y_)?MatrixQ, z___Rule] := 
  Module[{imax, jmax, min}, {imax, jmax} = Dimensions[x]; min = Min[x]; 
    Show[Graphics3D[Table[Flatten[{y[[i,j]], 
          cube[i, j, imax, jmax, min, x]}], {i, imax}, {j, jmax}], 
       Axes -> True, Lighting -> False, 
       PlotRange -> {{1/2, imax + 1/2}, {1/2, jmax + 1/2}, {min, Max[x]}}, z]
       ] /; Dimensions[x] == {imax, jmax}]
 
cube[i_, j_, imax_, jmax_, min_, x_] := 
  Module[{a = {}}, a = 
     {a, Polygon[{{i - 1/2, j - 1/2, x[[i,j]]}, 
        {i + 1/2, j - 1/2, x[[i,j]]}, {i + 1/2, j + 1/2, x[[i,j]]}, 
        {i - 1/2, j + 1/2, x[[i,j]]}}]}; 
    If[i == imax || x[[i,j]] > x[[i + 1,j]], 
     a = {a, Polygon[{{i + 1/2, j - 1/2, x[[i,j]]}, 
         {i + 1/2, j + 1/2, x[[i,j]]}, 
         {i + 1/2, j + 1/2, If[i == imax, min, x[[i + 1,j]]]}, 
         {i + 1/2, j - 1/2, If[i == imax, min, x[[i + 1,j]]]}}]}]; 
    If[i == 1 || x[[i,j]] > x[[i - 1,j]], 
     a = {a, Polygon[{{i - 1/2, j - 1/2, x[[i,j]]}, 
         {i - 1/2, j + 1/2, x[[i,j]]}, 
         {i - 1/2, j + 1/2, If[i == 1, min, x[[i - 1,j]]]}, 
         {i - 1/2, j - 1/2, If[i == 1, min, x[[i - 1,j]]]}}]}]; 
    If[j == jmax || x[[i,j]] > x[[i,j + 1]], 
     a = {a, Polygon[{{i - 1/2, j + 1/2, x[[i,j]]}, 
         {i + 1/2, j + 1/2, x[[i,j]]}, 
         {i + 1/2, j + 1/2, If[j == jmax, min, x[[i,j + 1]]]}, 
         {i - 1/2, j + 1/2, If[j == jmax, min, x[[i,j + 1]]]}}]}]; 
    If[j == 1 || x[[i,j]] > x[[i,j - 1]], 
     a = {a, Polygon[{{i - 1/2, j - 1/2, x[[i,j]]}, 
         {i + 1/2, j - 1/2, x[[i,j]]}, 
         {i + 1/2, j - 1/2, If[j == 1, min, x[[i,j - 1]]]}, 
         {i - 1/2, j - 1/2, If[j == 1, min, x[[i,j - 1]]]}}]}]; a]
