2016年7月29日 星期五

C129 油田數(VB版)


    Dim n As Integer, m As Integer          'n列 x m格
    Dim a(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 之間換行
            Dim t As Short = LineInput(fn) ' t 筆
            For k = 1 To t
                Dim nm() = LineInput(fn).Split(" ") ' n x m  油田 @油、*非
                n = nm(0) : m = nm(1)
                ' 讀入:將@轉為1、*轉為0 => a(i,j)

                For i = 1 To n
                    Dim line = LineInput(fn) ' 讀入一行
                    For j = 1 To m
                        If (Mid(line, j, 1) = "@") Then a(i, j) = 1
                    Next j
                Next i
                Dim ans = 0, mcnt = 0
                For i = 1 To n
                    For j = 1 To m
                        If a(i, j) = 1 Then '有1處油,以 dfs 遍歷此處
                            ans += 1
                            Dim cnt = 0
                            dfs(i, j, cnt)
                            If cnt > mcnt Then mcnt = cnt '此處的數量較大,設為mcnt
                        End If
                    Next
                Next

                PrintLine(3, ans & " " & mcnt)
            Next k
        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, ByRef cnt As Integer)
        a(i, j) = 0 : cnt += 1
        For d = 0 To 7    '八個方向 找 a(ni,nj) = 1
            Dim ni As Integer = i + di(d), nj As Integer = j + dj(d)
            If ni < 1 Or ni > n Or nj < 1 Or nj > m Then Continue For
            If a(ni, nj) = 1 Then     ' a(ni,nj)=1 :可擴散
                dfs(ni, nj, cnt)         ' 遞迴呼叫
            End If
        Next
    End Sub

in.txt 輸入檔
4
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@

out.txt 輸出檔
0 0
1 5
2 2
2 8

0 意見:

張貼留言