2016年7月29日 星期五

a753最大面積(VB版)

'  a753 最大面積 最多 AxB , 5<=A,B<=30
'  矩形一個 AXB ,查詢有 n 個, 每個高度為h 的最大面積,
'  如範例中 1的有7個、2的有5個、3的有6個、4的為0個 {1個的印0}

Dim A As Integer, B As Integer   '矩形 A x B
Dim v(100, 100) As Integer '假設最大為 100x100

    Private Sub Form1_Load( . . . ) Handles MyBase.Load
        FileOpen(1, "in.txt", OpenMode.Input)
        FileOpen(3, "out.txt", OpenMode.Output)
        For fn = 1 To 1
            If fn > 1 Then PrintLine(3) ' 第2個檔 in2 與 in1 之間換行
            '只有一個矩形 nxm
            Dim ab() = LineInput(fn).Split(" ") ' A x B  h=0~9
            A = ab(0) : B = ab(1)
            ' 數字以 空白 隔開

            For i = 0 To A - 1
                Dim dat() = LineInput(fn).Split(" ")  ' 讀入一行以空格分成 dat( )
                For j = 0 To B - 1
                    v(i, j) = dat(j)
                Next j
            Next i
            ' 建 htbl(9) h各高度的 最大區數量表
            Dim h As Integer
            Dim htbl(9) As Integer ' 0~9
            For i = 0 To A - 1
                For j = 0 To B - 1
                    h = v(i, j)
                    If h <> 0 Then '有1處 h 非 0
                        Dim cnt = 0
                        dfs(i, j, h, cnt)
                        If cnt > 1 And cnt > htbl(h) Then htbl(h) = cnt '此處的 h 數量較大,存入 htbl
                    End If
                Next
            Next
            ' n 筆查詢
            Dim n As Integer = LineInput(fn)
            For i = 1 To n
                h = LineInput(fn)
                PrintLine(3, "" & htbl(h))
            Next
        Next fn
        End
    End Sub

    Dim di() As Integer = {-1, 1, 0, 0}   '  , -1, 1, -1, 1} 本題只上下左右
    Dim dj() As Integer = {0, 0, -1, 1}   '  , -1, -1, 1, 1}

    Sub dfs(ByVal i As Integer, ByVal j As Integer, ByVal h As Integer, ByRef cnt As Integer)
        v(i, j) = 0 : cnt += 1
        For d = 0 To 3  '四個方向 找 v(ni,nj) = h
            Dim ni As Integer = i + di(d), nj As Integer = j + dj(d)
            If ni < 0 Or ni >= A Or nj < 0 Or nj >= B Then Continue For
            If v(ni, nj) = h Then ' v(ni,nj)=h :可擴散
                dfs(ni, nj, h, cnt)
            End If
        Next
    End Sub
in.txt 輸入檔
5 7
1 1 1 4 1 1 1
1 2 2 3 1 3 1
1 2 3 3 3 1 1
2 2 3 3 2 2 2
4 3 2 2 1 2 2
4
1
2
3
4

out.txt 輸出檔
7
5
6
0

0 意見:

張貼留言