Modular Programming - C#


  • 1
    S
    public class Solution {
        
        List<IList<string>> res = new List<IList<string>>();  
        int n;
        
        public IList<IList<string>> SolveNQueens(int n) {
            this.n = n;
            var arr = new char[n][];
            InitializeArray(arr);
            Helper(arr, 0);
            return res;
        }
        
        void Helper(char[][] arr, int col)
        {
            if(col == n)
            {
                ConvertStringArr(arr);
                return;
            }
            
            for(int row = 0; row < n; row++)
            {
                if(IsValid(arr, row, col))
                {
                    arr[row][col] = 'Q';
                    Helper(arr, col+1);   
                    arr[row][col] = '.';
                }
            }
        }
        
        bool IsValid(char[][] arr, int x, int y)
        {
            for(int i = 0; i < n; i++)
            {
                for(int j = 0; j < y; j++)
                {
                    if(arr[i][j] == 'Q' && ((i == x) || x == (y-j) + i || x == i - (y-j)))
                        return false;
                }
            }
            return true;
        }
        
        void ConvertStringArr(char[][] arr)
        {
            var list = new List<string>();
            for(int i = 0; i < n; i++)
            {
                list.Add(new string(arr[i]));
            }
            res.Add(list);
        }
        
        void InitializeArray(char[][] arr)
        {
            for(int i = 0; i < n; i++)
            {
                arr[i] = new char[n];
                for(int j = 0; j < n; j++)
                {
                    arr[i][j] = '.';
                }
            }
        }
    }
    

Log in to reply
 

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