2017-09-13 85 views
2

我遇到與此作業有關的問題。我要打印一個不能是方形的螺旋矩陣,換句話說,用戶應該輸入行數和列數。非正方形螺旋矩陣打印不正確

 Console.Write("Enter n: "); 
     int n = int.Parse(Console.ReadLine()); 
     Console.Write("Enter m: "); 
     int m = int.Parse(Console.ReadLine()); 
     int[,] matrix = new int[n,m]; 
     int row = 0; 
     int col = 0; 
     string direction = "right"; 
     int maxRotations = n * m; 

     for (int i = 1; i <= maxRotations; i++) 
     { 
      if (direction == "right" && (col > n - 1 || matrix[row, col] != 0)) 
      { 
       direction = "down"; 
       col--; 
       row++; 
      } 
      if (direction == "down" && (row > n - 1 || matrix[row, col] != 0)) 
      { 
       direction = "left"; 
       row--; 
       col--; 
      } 
      if (direction == "left" && (col < 0 || matrix[row, col] != 0)) 
      { 
       direction = "up"; 
       col++; 
       row--; 
      } 

      if (direction == "up" && row < 0 || matrix[row, col] != 0) 
      { 
       direction = "right"; 
       row++; 
       col++; 
      } 

      matrix[row, col] = i; 

      if (direction == "right") 
      { 
       col++; 
      } 
      if (direction == "down") 
      { 
       row++; 
      } 
      if (direction == "left") 
      { 
       col--; 
      } 
      if (direction == "up") 
      { 
       row--; 
      } 
     } 

     // displej matrica 

     for (int r = 0; r < n; r++) 
     { 
      for (int c = 0; c < m ; c++) 
      { 
       Console.Write("{0,4}", matrix[r,c]); 
      } 
      Console.WriteLine(); 

     } 
     Console.ReadLine(); 
    } 

我的問題目前不在印刷,並在同一螺旋被打印。換句話說,這個螺旋線有點混亂。 如果我運行代碼和行6號,並輸入4,因爲我得到的列數如下:

1 2 3 4 0 24 
12 13 14 5 0 23 
11 16 17 18 19 22 
10 9 8 7 20 21 

我到底做錯了什麼?

+0

你不是從數組中心開始的 –

+1

我想'if(direction ==「right」&&(col> n - 1 || matrix [row,col]!= 0))'should如果(方向==「右」&&(col> m - 1 || matrix [row,col]!= 0))(** m **而不是n) – Fildor

+0

@YairHalberstadt我猜螺旋要走了「向內」而不是「向外」。 – Fildor

回答

0

你的前兩個條件檢查相同的邊界(N):

if (direction == "right" && (col > n - 1 || matrix[row, col] != 0)) 
if (direction == "down" && (row > n - 1 || matrix[row, col] != 0)) 

我猜 「正確」 的邊界應該是m

if (direction == "right" && (col > m - 1 || matrix[row, col] != 0)) 

這就是爲什麼它是「轉向」的早期:n是4,而這正是它轉向的地方。其餘的都是後續錯誤。

+0

如果OP已經命名變量r&c而不是n&m,它可能會更加明顯。 – spodger

+0

@spodger事實上,我不認爲「r」和「c」對「n」和「m」有很大的改進。但是你真的可以通過var名稱闖入可怕的戰鬥。如果我必須提出建議,我會將它們命名爲「maxRow」和「maxCol」。但那只是我個人的風格。或者,也許「寬度」和「高度」... – Fildor

+1

就是這樣。感謝一堆:) –