C# Solution by marking edges


  • 0
    L
    public void SetZeroes(int[,] matrix) {
        int m = matrix.GetLength(0), n = matrix.GetLength(1);
        bool[] edge = new bool[4];
        for (int i = 0; i < m; i++){
            if (matrix[i, 0] == 0) edge[0] = true;
            if (matrix[i, n - 1] == 0) edge[1] = true;
        }
        for (int i = 0; i < n; i++){
            if (matrix[0, i] == 0) edge[2] = true;
            if (matrix[m - 1, i] == 0) edge[3] = true;
        }
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (matrix[i, j] == 0)
                    matrix[0, j] = matrix[i, 0] = 0;
        for (int i = 1; i < m - 1; i++)
            if (matrix[i, 0] == 0)
                for (int j = 0; j < n; j++)
                    matrix[i, j] = 0;
        for (int j = 1; j < n - 1; j++)
            if (matrix[0, j] == 0)
                for (int i = 0; i < m; i++)
                    matrix[i, j] = 0;
        for (int i = 0; i < edge.Length; i++)
            if (edge[i])
                switch (i){
                    case 0:
                        for (int j = 0; j < m; j++) matrix[j, 0] = 0; break;
                    case 1:
                        for (int j = 0; j < m; j++) matrix[j, n - 1] = 0; break;
                    case 2:
                        for (int j = 0; j < n; j++) matrix[0, j] = 0; break;
                    case 3:
                        for (int j = 0; j < n; j++) matrix[m - 1, j] = 0; break;
                }
    }

Log in to reply
 

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