Const MaxN As Integer = 10
Dim d, r As Integer ' //d行進方向, r反彈類型
Dim dx() As Integer = {-1, 1, 1, -1} ' //0右上、1左上、2左下、3右下
Dim dy() As Integer = {1, 1, -1, -1} ' // 某方向行進的位移
Dim rx() As Integer = {0, 0, -1, 1, 0} ' //0上、1下、2左、3右 、4四角
Dim ry() As Integer = {-1, 1, 0, 0, 0} ' //四邊反彈的位移{非四角}
Dim a(MaxN, MaxN) As Integer
Dim EX, EY As Integer '寬、高
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FileOpen(1, "in1.txt", OpenMode.Input)
FileOpen(2, "in2.txt", OpenMode.Input)
FileOpen(3, "out.txt", OpenMode.Output)
Dim sx, sy As Integer '起點
For fn = 1 To 2
If fn = 2 Then PrintLine(3) 'in1,in2間 空一列
Dim n As Short = LineInput(fn)
For k = 1 To n
Dim WH() = LineInput(fn).Split(" ") ' 讀 EX , EY
EX = WH(0) : EY = WH(1)
For i = 1 To EY
Dim dat() = LineInput(fn).Split(" ")
For j = 1 To EX
a(i, j) = dat(j - 1)
Next
Next
Dim xyd() = LineInput(fn).Split(" ")
sx = xyd(0) : sy = xyd(1) : d = xyd(2) - 1 ' d改為從 0~3
Dim sum As Integer = gsum(sx, sy, d) '呼叫 gsum(起點、方向) 得 經過數字和
PrintLine(3, "" & sum) '印出數字和
Next k
Next fn
End
End Sub
Function gsum(ByVal x, ByVal y, ByVal d) As Integer
Dim nx, ny As Integer '下一格
Dim t As Integer = 0 '反彈次數
Dim sum As Integer = 0 '數字加總
Do While (t < 4)
sum += a(y, x) '走至(x,y)格,將數字加入
nx = x + dx(d) : ny = y + dy(d) '算下一格的位置
Dim xx As Boolean = (nx < 1 Or nx > EX) '下一格的 nx 座標是否超界
Dim yy As Boolean = (ny < 1 Or ny > EY) '下一格的 ny 座標是否超界
If (xx Or yy) Then '有超出邊界
If (xx And yy) Then '四個角落反彈
r = 4 '反彈類型
d = (d + 2) Mod 4 '反彈後方向
Else
If xx And (d = 2 Or d = 3) Then
r = 0 : d = 5 - d
ElseIf xx And (d = 0 Or d = 1) Then
r = 1 : d = 1 - d
ElseIf yy And (d = 0 Or d = 3) Then
r = 2 : d = 3 - d
ElseIf yy And (d = 1 Or d = 2) Then
r = 3 : d = 3 - d
End If
End If
nx = x + rx(r) : ny = y + ry(r) '反彈後的 新座標
t += 1 '反彈次數加1
End If
x = nx : y = ny
Loop
Return sum
End Function
in1.txt
2
3 3
1 3 9
-4 -6 5
8 2 -7
3 1 1
3 4
2 5 8
3 -1 -6
7 8 -9
2 0 3
1 1 2
in2.txt
2
3 5
1 2 3
4 5 6
7 8 9
0 -2 -5
-8 -9 7
3 4 4
3 5
1 2 3
4 5 6
7 8 9
0 -2 -5
-8 -9 7
1 3 3
out.txt
44
10
15
28
0 意見:
張貼留言