function C = components_2d ( A )

%*****************************************************************************80
%
%% components_2d() assigns contiguous nonzero pixels to a common component.
%
%  Discussion:
%
%    On input, the A array contains values of 0 or 1.
%
%    The 0 pixels are to be ignored.  The 1 pixels are to be grouped
%    into connected components.
%
%    The pixel A(I,J) is "connected" to the pixels A(I-1,J), A(I+1,J),
%    A(I,J-1) and A(I,J+1), so most pixels have 4 neighbors.
%
%    (Another choice would be to assume that a pixel was connected
%    to the other 8 pixels in the 3x3 block containing it.)
%
%  Picture:
%
%    Input A:
%
%      0  2  0  0 17  0  3
%      0  0  3  0  1  0  4
%      1  0  4  8  8  0  7
%      3  0  6 45  0  0  0
%      3 17  0  5  9  2  5
%
%    Output:
%
%      C:
%
%      0  1  0  0  2  0  3
%      0  0  2  0  2  0  3
%      4  0  2  2  2  0  3
%      4  0  2  2  0  0  0
%      4  4  0  2  2  2  2
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    11 March 2025
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer A(M,N), the pixel array.
%
%  Output:
%
%    integer C(M,N), the component array.
%
  [ m, n ] = size ( A );
%
%  Initialization.
%
  C = zeros ( m, n );
  component_index = 0;

  plist = [];

  for i2 = 1 : m
    for j2 = 1 : n

      if ( A(i2,j2) ~= 0 && C(i2,j2) == 0 )

        plist = [ plist; i2, j2 ];
        component_index = component_index + 1;

        while ( ~ isempty ( plist ) )

          i = plist(end,1);
          j = plist(end,2);
          plist(end,:) = [];
          C(i,j) = component_index;

          if ( 1 <= i-1 && A(i-1,j) ~= 0 && C(i-1,j) == 0 )
            plist = [ plist; i - 1, j ];
          end
          if ( i+1 <= m  && A(i+1,j) ~= 0 && C(i+1,j) == 0 )
            plist = [ plist; i + 1, j ];
          end
          if ( 1 <= j - 1 && A(i,j-1) ~= 0 && C(i,j-1) == 0 )
            plist = [ plist; i, j - 1 ];
          end
          if ( j+1 <= n && A(i,j+1) ~= 0 && C(i,j+1) == 0 )
            plist = [ plist; i, j + 1 ];
          end
        end
      end
    end
  end

  return
end
