Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class GetNeighbors
  4. {
  5. public static void main(String args[])
  6. {
  7. Scanner kb = new Scanner(System.in);
  8.  
  9. System.out.println("Enter how many rows will be in the matrix");
  10. int row=kb.nextInt();
  11. System.out.println("Enter how many columns will be in the matrix");
  12. int col=kb.nextInt();
  13.  
  14. int[][] mat=new int[row][col];
  15. initList(mat,row,col);
  16. while(assign(mat,row,col) >=0)
  17. {
  18. assign(mat,row,col);
  19. }
  20. }
  21. public static void initList(int[][] mat,int row,int col)
  22. {
  23. for(int r=0; r<row; r++)
  24. {
  25. System.out.println("");
  26. for(int c=0; c<col; c++)
  27. {
  28. mat[r][c]=(int)(Math.random()*1000+1);
  29. System.out.printf("%5s",mat[r][c]);
  30. }
  31.  
  32. }
  33. }
  34. public static int assign(int[][] matrix,int row,int col)
  35. {
  36. int r = 0;
  37. int c = 0;
  38. Scanner keyboard=new Scanner(System.in);
  39. System.out.println("\nEnter the row number for an element");
  40. r=keyboard.nextInt();
  41. if(r == -1)
  42. {
  43. return -1;
  44. }
  45. System.out.println("Enter the column number for an element");
  46. c=keyboard.nextInt();
  47. if(r>=row || c >= col)
  48. {
  49. System.out.println("House does not exist");
  50. return 0;
  51. }
  52. System.out.println("Requested neighbors for element at row "+r+", col "+c+" "+"("+matrix[r][c]+")");
  53.  
  54. if(r-1<row&&r-1>0)
  55. {
  56. System.out.println("North "+matrix[r-1][c]);
  57. }
  58. else
  59. {
  60. System.out.println("North -1");
  61. }
  62. if(r+1<row&&r+1>0)
  63. {
  64. System.out.println("South "+matrix[r+1][c]);
  65. }
  66. else
  67. {
  68. System.out.println("South -1");
  69. }
  70. if(c-1<col&&c-1>0)
  71. {
  72. System.out.println("West "+matrix[r][c-1]);
  73. }
  74. else
  75. {
  76. System.out.println("West -1");
  77. }
  78. if(c+1<col&&c+1>0)
  79. {
  80. System.out.println("East "+matrix[r][c+1]);
  81. }
  82. else
  83. {
  84. System.out.println("East -1");
  85. }
  86. return 0;
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement