1. Basic settings
In the 20×20 chessboard matrix, set the black stone to 1 and the empty value to 0
Now it is necessary to count the size and number of null values (connected components) and mark them, as shown in the following figure:
and so on
Among them, the largest connected component is as follows:
2. Matlab program
The following is a Matlab program with connected component size 6 marked in red
clear,clc,close all m = 20; n = 20; markersize = floor(80-(max([m n]))); rng('default'); A = randn(m,n); A(abs(A)<=1) = 1; A(abs(A)>1) = 0; Ar = 1-A; cc4 = bwconncomp(Ar,4); L4 = labelmatrix(cc4); counts = []; for i = 1:numel(cc4.PixelIdxList) idx = cc4.PixelIdxList{1,i}; Ar(idx) = numel(cc4.PixelIdxList{1,i}); counts(i) = numel(cc4.PixelIdxList{1,i}); end size=flip(unique(counts)); fprintf('Number\t\tSize of connected components\t\tNumber\ '); for i = 1:numel(size) fprintf('%d\t\t\t%d\t\t\t%d\ ',i,size(i),sum(counts==size(i))); end fprintf('Total number of connected components: %d\ ',cc4.NumObjects); mark = 6; % size of connected components to be marked Ar(Ar~=mark)=0; fprintf('Original chessboard matrix:\ '); disp(A); % sunspot is 1, null value is 0 fprintf('Red marked checkerboard matrix:\ '); disp(Ar); % red is 1, the rest is 0 go(A,markersize,m,n,[],[],[]) go(A,markersize,m,n,Ar,mark,sum(counts==mark)) function go(A,markersize,m,n,Ar,mark,count) figure('color',[1 1 1],'position',[600,100,400*1.5,400*1.5]); hold on spy(A,'k',markersize); spy(Ar,'r',markersize); axis([1 n 1 m]); xticks([1:n]); yticks([1:m]); xlabel("The size of the connected components marked in red is: " + mark + ", and the number is: " + count); ax = gca; ax.GridColor = [0 .5 .5]; ax.GridLineStyle = '-'; ax.GridAlpha = 0.5; ax.Layer = 'top'; ax.XRuler.TickLabelGapOffset = 20; ax.YRuler.TickLabelGapOffset = 20; ax.YAxis.Label.Visible = 'off'; grid on end
3. Output results
number connected component size number 1 10 1 2 8 1 3 7 2 4 6 4 5 5 2 6 4 2 7 3 3 8 2 12 9 1 22 Total number of connected components: 49 Original chessboard matrix: 1 1 1 0 0 1 0 1 1 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