Most Beautiful C# Code


  • 0
    C

    public class Position
    {
    public int Row { get; set; }
    public int Column { get; set; }

    public Position(int row, int column)
    {
        this.Row = row;
        this.Column = column;
    }
    

    }

    public class Solution {

    public void WallsAndGates(int[,] rooms) {
        // error cases
        // no gates
        // gate surrounded by walls
        
        for (int row=0; row <= rooms.GetUpperBound(0); row++)
        {
            for (int col=0; col <= rooms.GetUpperBound(1); col++)
            {
                // found a gate
                if (rooms[row, col] == 0)
                {
                    TraverseAllPaths(rooms, row, col, 1);
                }
            }
        }
    }
    
    public void TraverseAllPaths(int[,] rooms, int r, int c, int depth)
    {
        List<Position> validCells = GetNotVisitedNodes(rooms, r, c, depth);
        
        for (int i=0; i < validCells.Count; i++)
        {
            // flip the node to visited by changing the value to depth
            rooms[validCells[i].Row, validCells[i].Column] = depth;
            TraverseAllPaths(rooms, validCells[i].Row, validCells[i].Column, depth + 1);
        }
    }
    
    public List<Position> GetNotVisitedNodes(int[,] rooms, int r, int c, int minDepth)
    {
        List<Position> validCells = new List<Position>();
        
        if (IsValidCell(rooms, r + 1, c, minDepth))
        {
            validCells.Add(new Position(r + 1, c));
        }
        
        if (IsValidCell(rooms, r, c + 1, minDepth))
        {
            validCells.Add(new Position(r, c + 1));
        }
        
        if (IsValidCell(rooms, r - 1, c , minDepth))
        {
            validCells.Add(new Position(r - 1, c));
        }
        
        if (IsValidCell(rooms, r, c - 1, minDepth))
        {
            validCells.Add(new Position(r, c - 1));
        }
        
        return validCells;
    }
    
    public bool IsValidCell(int[,] rooms, int r, int c, int minDepth)
    {
        // we only execute only if the value is with in the 
        if (r < 0 || c < 0 || r > rooms.GetUpperBound(0) || c > rooms.GetUpperBound(1))
        {
            return false;
        }
        
        if (rooms[r, c] == -1)
        {
            return false;
        }
        
        // had a value but it is less than the minDepth that we expecting to write
        if (rooms[r, c] <= minDepth)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    

    }


Log in to reply
 

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