C# - simple 2 pass with row and col counting arrays


  • 0

    First make a pass through the matrix and any found 'B' count a point in each row and column. Then make a second pass and any found 'B' if the row and col counters are equal to 1 this is a lonely 'B'.

        public int FindLonelyPixel(char[,] picture) 
        {
            int[] rows = new int[picture.GetLength(0)];
            int[] cols = new int[picture.GetLength(1)];
            
            for (int i = 0; i < picture.GetLength(0); i++)
            {
                for (int j = 0; j < picture.GetLength(1); j++)
                {
                    if (picture[i,j] == 'B') { rows[i]++; cols[j]++; }
                }   
            }
            
            int cnt = 0;
            for (int i = 0; i < picture.GetLength(0); i++)
            {
                for (int j = 0; j < picture.GetLength(1); j++)
                {
                    if (picture[i,j] == 'B' && rows[i] == 1 && cols[j]== 1) cnt++;
                }   
            }
            
            return cnt;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.