C# - BFS start with all 0's - change 1's to max int


  • 0
        public IList<IList<int>> UpdateMatrix(IList<IList<int>> matrix) {
            Queue<int> queue = new Queue<int>();
            for (int i = 0; i < matrix.Count; i++)
            {
                for (int j = 0; j < matrix[i].Count; j++)
                {
                    if (matrix[i][j] == 0)
                    {
                        queue.Enqueue(i);
                        queue.Enqueue(j);
                    }
                    else
                    {
                        matrix[i][j] = int.MaxValue;
                    }
                }
            }
            
            while (queue.Count > 0)
            {
                int i = queue.Dequeue();
                int j = queue.Dequeue();
                
                if (i > 0 && matrix[i][j] + 1 < matrix[i-1][j])
                {
                    matrix[i-1][j] = matrix[i][j] + 1;
                    queue.Enqueue(i-1);
                    queue.Enqueue(j);
                }
                if (i < matrix.Count - 1 && matrix[i][j] + 1 < matrix[i+1][j])
                {
                    matrix[i+1][j] = matrix[i][j] + 1;
                    queue.Enqueue(i+1);
                    queue.Enqueue(j);
                }
                if (j > 0 && matrix[i][j] + 1 < matrix[i][j-1])
                {
                    matrix[i][j-1] = matrix[i][j] + 1;
                    queue.Enqueue(i);
                    queue.Enqueue(j-1);
                }
                if (j < matrix[i].Count - 1 && matrix[i][j] + 1 < matrix[i][j+1])
                {
                    matrix[i][j+1] = matrix[i][j] + 1;
                    queue.Enqueue(i);
                    queue.Enqueue(j+1);
                }
            }
            
            return matrix;
        }
    

Log in to reply
 

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