2016年7月20日 星期三

dfs-1(vb版參考)

程式碼:
    Dim a(100, 100) As Integer
    Dim m As Integer, n As Integer
    Private Sub Form1_Load( ...  ) Handles MyBase.Load
        FileOpen(1, "in1.txt", OpenMode.Input)
        FileOpen(2, "in2.txt", OpenMode.Input)
        FileOpen(3, "out.txt", OpenMode.Output)
        For fn = 1 To 2  ' two in?.txt file
            Dim t As Short = LineInput(fn)  '每檔有 t 組資料
            For k = 1 To t              '處理 第k組
                Dim mn() = LineInput(fn).Split(" ")   '讀 m n
                m = mn(0) : n = mn(1)
                   For i = 0 To m - 1        'm 列
                    Dim s = LineInput(fn)  '讀入一列

                    For j = 0 To n - 1    ' 設定每一格的 a(i,j)值
                        a(i, j) = IIf(Mid(s, j + 1, 1) = "1", 1, 0)
                     Next
                Next

                Dim ans = 0  '水窪數量
                Dim maxn = 0 '最大窪值
                Dim cnt = 0 '某一處窪值

                For i = 0 To m - 1
                    For j = 0 To n - 1
                        If a(i, j) = 1 Then   '有一處
                            ans += 1           '計次加1
                            dfs(i, j, cnt)      '將此處(i,j)及連通處皆設為0
                            If cnt > maxn Then maxn = cnt
                        End If
                    Next
                Next
                PrintLine(3, ans & "," & maxn)  '印出答案 窪數,最大窪值
            Next   ' for k
            If fn = 1 Then PrintLine(3)
        Next     ' for fn
        End
    End Sub

    Dim dr() As Integer = {-1, 1, 0, 0}    '列位移:上下左右
    Dim dc() As Integer = {0, 0, -1, 1}   '行位移:上下左右
    Sub dfs(ByVal i As Integer, ByVal j As Integer, ByRef cnt As Integer)
        Dim stki(10000) As Integer, stkj(10000) As Integer
        Dim p As Integer = 0   '堆疊內目前的數量
        cnt = 0
        stki(p) = i : stkj(p) = j : p += 1           ' push i,j to stack 加入堆疊
           a(i, j) = 0 : cnt += 1
        Dim ni As Integer, nj As Integer
        Do While p > 0                             ' stack not empty  堆疊非空繼續
            p -= 1 : i = stki(p) : j = stkj(p) ' pop i,j from stack
             For d = 0 To 3
                ni = i + dr(d) : nj = j + dc(d)
                If ni < 0 Or ni >= m Or nj < 0 Or nj >= n Then Continue For    '超出範圍
                If a(ni, nj) = 1 Then                                     '有連通, 將ni,nj push to stack
                      stki(p) = ni : stkj(p) = nj : p += 1           ' push ni,nj to stack
                    a(ni, nj) = 0 : cnt += 1
                End If
            Next
        Loop
    End Sub

in1.txt
2
7 7
0000111
0110101
0010101
1010000
1010011
0000001
0111100
7 7
1000111
0110101
0010010
1100000
0011011
1000001
0111100
in2.txt
3
1 8
110000010
5 5
00001
01101
01001
11101
11001
3 5
01001
00110
01001

0 意見:

張貼留言